Variables¶
Variables are like boxes: you can store anything in them and then put a label on it. The label doesn't need to match the contents, but it's really helpful if it does.
We store a value into a variable with the =
(single equals) operator. This creates a statement that has an effect (to store a value in the "box" with the specified label).
x = 2
Once a variable exists, we can use it as an expression (thing that evaluates to a value):
x
2
But the variable must exist first! Referencing a label for a box that hasn't been created yet generates an error:
y
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[4], line 1 ----> 1 y NameError: name 'y' is not defined
Variables will always hold the same value until they are re-assigned. Moreover, the expression on the right-hand side of the =
is fully evaluated at assignment time.
x = 2 + 2 # stores 4, i.e. the result of the `2 + 2` expression
We can do a number of things in the meantime, including using x
...
y = x
z = 65
n = z + 5.4 / x
m = 11.2 * x
... but x will remain unchanged.
x
22
x * 2 + 32 / 9
11.555555555555555
22 = x
22 = 4
Cell In[10], line 1 22 = x ^ SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
x = 22
x
22
pi = 3.14
avogadro = 6
avogadro
6
y = 25
x_and_y = x + y
x_and_y
47
x123 = 123
x123
123
x/y
0.88
Go to this code in PythonTutor. What's the output?
Aside: print
¶
In the Python Interpreter (or the last line of code in a notebook cell), the value of expressions is automatically shown. Often, we need to be more explicit about when values are shown in our terminal or on screen. This is where print
comes in.
print("Hello World!")
"Hello World!"
This is especially helpful when seeing intermediate values in a short program:
x = 2 + 4
print(x)
y = 3 + x
print(y)
x = y
print(x)
6 9 9
x = 2 + 4
print(x)
6
print("Hello")
Hello
x = print(42)
42
print(x)
None
Boolean Expressions¶
So if we have variables that can have arbitrary values, then we might at some point need a way to determine a variable's stored value without changing it. This is where boolean expressions come in.
x = 2
x < 5
True
x > 5
False
22 >= 22
True
not 22 == 22
False
not x < 5 or x == 2
True
False or False
False
False and True
False
# What's printed out here?
temp = 72
is_liquid = temp > 32 and temp < 212
print(is_liquid)
temp = 300
print(is_liquid)
True True
Strings¶
Strings are a type of value that can hold arbitrary letters, symbols, numbers, etc. They are denoted by paired single ('
) or double ("
) quotes.
name = "Alessia"
name
thing_one = ""
thing_two = 0
thing_three = print("Hello")
thing_one == thing_two == thing_three