Outside Resources:
Interactive Python – Variables and Types
TheNewBoston – Python Numbers and Math
TheNewBoston – Python Variables
A variable is a named memory location that your program uses to store information.
Example:
total = 25 language = "Python" rate = 0.065 finished = False
Each of these example variables stores a different type of data:
Example Data | Type | Explanation |
25 | int | Integer, whole number |
“Python” | str | String, text data |
0.065 | float | Floating decimal number |
False | bool | Boolean, True or False |
Type up the program above run it. What happens?
…
Nothing happens. Storing information as a variable happens behind the scenes.
You can print a value at a later time:
print(total)
You can also check a variable’s value from the Python Console. Find your Python Console’s prompt, which might look like “>” or “>>>”, and type the name of one of your variables. (hit enter)
It should report the the value:
>>> total 25 >>> language 'Python'
Assigning Values
To assign means to make the variable equal a certain value.
Use the equals “=” operator to assign values.
The variable goes on the left of the equal sign, and the value goes on the right side.
# correct way to do it x = 4 # wrong way to do it 4 = x
The second one doesn’t work, because you’re not allowed to redefine what the number 4 means.
Changing Variable Values
You can assign new values to a variable using math or other operations.
Examples:
x = 30 x = x + 8 print(x)
In the second line of code, we set x equal to whatever the previous value of x was plus another 8. This, of course, equals 38.
Increment Assign
The += operator provides a shortcut for adding an amount to a variable’s previous value.
The following two lines of the code are equivalent:
x = x + 1 x += 1
Similarly, Python has operators to assign and subtract, multiply, or divide in one step.
x = 12 x -= 3 # subtract and assign x *= 2 # multiply and assign x /= 4 # divide and assign
Note: this doesn't work if you switch the "+" and "=" around.
x = 5 # Typed incorrectly: x =+ 1
Python interprets that like this:
x = +1
So Python makes x equal 1 instead of adding 1 to the previous value.
Python Variables are not “linked”
Consider this example code. What will happen?
b = 39 a = b b = 7 print(a)
OUTPUT:
39
After “a = b,” a has a value of 39.
The next line, “b = 7,” does not change a, so a still equals 39.