CS 110A Lecture Notes - Simple Python Data - Chapter 2
Making You Own Notes for Useful Commands
Data Types and Variables
Some of the most common data types:
- Floating Point - a term referring to real number approximations stored in computers
- str - string (text), any number of characters.
- float - floating point number, can be positive, negative or zero.
- int - integer (whole) number, can be positive, negative or zero.
Calculations and Assignments
- Arithmetic operators (they work on numeric datatypes only, not strings):
*
for multiplication
**
for exponentiation (powers), e.g. 2**3 is 23 which equals 8.
+
for addition
-
for subtraction
/
for division
//
for integer division, e.g. 14//3 equals 4
%
for modulus (the remainder from integer division), e.g. 14%3 equals 2
=
for assignment (storing the result of expression at right in variable at left)
- The order of operations is just like in mathematics: exponentiation (**) is processed first, followed by multiplication (*), division (/, //), and modulus(%), then addition (+) and subtraction (-). After all of that, the assignment operator (=) is processed. Parentheses may be used to specify a different of order of operations.
- Note that variable assignments can be changed. For example:
a = 5
b = a # b stores a copy of a's value: both are 5.
print(a, b)
a = 3 # a now stores 3, but b is still 5.
print(a, b)
Programming Style
- Programs are written to be read by other humans as well as the computer.
- You should always have Comments at the top of your program, stating your name, the name of
your program source file, the name of the class and assignment, and a brief description of what the
program does.
- Comments should also be used to explain hard-to-understand code, and to summarize big steps such as
functions and sometimes loops.
- Use helpful variable names (strive for self-commenting code - clear without comments to explain it.)
- Provide a good user interface, including prompting for inputs and explaining outputs.
calcDemo.py: Here is an example demonstrating how variables and data types work in calculations, and with simple input.
In-class exercise: Write a program to calculate and output the average of three test grades input by the user. Here is some sample output:
Please enter the first test score 90
Please enter the second test score 81.2
Please enter the third test score 88.77
The average grade is 86.65666666666665