s
Basic Programming Constructs · a running review, since you have done most of this before
In your own words: what is a variable, and what does it do?
Once a variable is assigned, using its name anywhere in the code gets you its currently assigned value, the most recent value the variable was given.
Line 1 assigns 5 to x. Lines 2 and 3 both read it, they do not change it.
x starts as an int, then gets reassigned to a bool.
Python lets a variable hold any type of data, and a new assignment always overwrites what was there before.
_) are allowed.print or True) are off limits as names.numberOfRabbits = 40
thisIsFun = True
number_of_rabbits = 40
this_is_fun = True
4thGradeMath = 'arithmetic' # illegal: starts with a digit
What kind of error does Python display when it runs this code?
IllegalVariableNameErrorSyntaxErrorUnknownErrorSemanticErrorA SyntaxError means Python could not understand the grammar of your code, before it ever starts running. It is like a sentence with its words out of order: the reader stops at the mistake and cannot continue until it is fixed.
Each box on the next slide is a variable. Read the highlighted line of code, work out what value it assigns, then drag (or click, then click the box) the matching value chip into the right box. Some chips are decoys, values you'd get from a common misreading, so evaluate the line before you place a chip.
All boxes traced correctly. That's assignment: a name always holds its most recently assigned value.
=) stores a value in a named box; reading the name later gets whatever was most recently assigned.A constant is a name attached to a value, just like a variable, except the value is not meant to change while the program runs.
Python itself comes with a few names built in, so you never assign them yourself.
True and False are logical values,
and None stands for "no value," used whenever nothing else makes sense.
The math module packages up useful constants, like math.pi, so you never have to type them out by hand.
import math is what unlocks them.
# is a comment. Python ignores it completely, comments exist to help you (and other humans), not the computer.
What happens if you delete the comments from the previous example and then run it?
Here is the same program with the comments stripped out. Run it and confirm the output is identical, comments never change what the code does.
import math
print(math.pi)
print(math.e)
const or final keyword; nothing stops you from reassigning any name.MAX_SPEED = 120
GRAVITY = 9.8
currentSpeed = 0
Nothing crashes if you reassign MAX_SPEED, the all-caps name is the only thing telling you (and Python) not to.
True, False, and None are built into Python; you never assign them yourself.import math unlocks built-in constants like math.pi and math.e.# is a comment: for humans, ignored by Python.const keyword; UPPER_SNAKE_CASE is just a naming convention for your own constants.
Python sorts every value into a type: what kind of thing it is.
type(123) reports it obscurely as <class 'int'>, you can just read that as int.
123 is an integer, in Python, it has the type int.
print(type(123))int vs floatfloat, so 42.0 is a float, not an int.78238723874327827348724783 is still just an int.4.1e+48.123
78238723874327827348724783
4.56
42.0
4.1e+48
bool, str, NoneTypeTrue and False are the only bool values, we already met these as constants.str holds text: single or double quotes both work, but the opening and closing quote must match. The empty string '' is still a string, just with length 0.None is the one and only value of type NoneType.type is a type too
int is a type. But what is the type of int itself?
Every Python type is a value, and every type's type is… type.
print(type(int))print(type(0.))What is type(0.)?
intfloatstrprint(type('0.'))What is type('0.')?
intfloatstr
Run this side by side and check the two lines of output against your answers:
0. without quotes is a float, and '0.' inside quotes is a str.
print(type(0.))
print(type('0.'))
Drag (or click, then click the bin) each value chip into the type it belongs to. A few pairs look alike: quotes make a string, a decimal point makes a float, so read each value carefully before you sort it.
All 8 values sorted. Quotes make a string, a decimal point makes a float, and the rest come down to what the value actually is.
type(x) tells you which one.int (whole numbers) and float (has a decimal point, or written in scientific notation).bool, str, and NoneType round out the core types we've met so far.
An operator is a symbol that performs some computation.
+ is the addition operator, so 2 + 3 is 5.
+ - * / ** // %.bool.bool values: and or not.+=, are a shorthand for updating a variable.* is the multiplication operator./ is the division operator./ always returns a float, so 6 / 2 is 3.0, not the int 3.** is exponentiation: 2 ** 3 is 2 to the 3rd power, 8.// is floor division: regular division, then rounded down. 11 / 4 is 2.75, so 11 // 4 is 2.% is remainder (or "modulo", or "mod"): the leftover after division. 14 % 5 is 4, since 14 divided by 5 leaves a remainder of 4.
A runtime error means Python understood your code just fine and started running it, but hit an operation partway through that it cannot actually perform. Dividing by 0 is a classic example: there is no answer, so Python raises a ZeroDivisionError and stops.
Even numbers are divisible by 2, so if x is even, x % 2 is 0.
If x % 2 is 1, then x is odd.
x = 7
print(x % 2)Comparison operators compare two values and return a bool.
== equal to · != not equal to< less than · <= less than or equal> greater than · >= greater than or equal= assigns a value. A double == compares two values. Mixing these up is a common bug.
False?print(1 == 2)print(3 != 4)print(5 < 6)print(7 <= 8)print(9 >= 9)print(10 > 10)and: true only if both sides are true.or: true if either side (or both) is true.not: flips a value, true becomes false and back.
Comparison and logical operators combine to build bigger conditions. Work out each comparison first, then apply and, or, or not.
True?Given x = 5 and y = 7:
print((3 < x) and (y < x))print((3 < x) or (y < x))print(not (x >= y - 2))+= shorthand
x += y is basically the same as x = x + y. It is mostly a convenience, but it is common, so you need to be comfortable reading it.
Besides +=, every arithmetic operator has a matching assignment operator. x -= y is the same as x = x - y, and so on.
+=-=*=/=//=%=**=b = 7
b /= 2
3.5
c = 7
c //= 2
3
d = 7
d %= 2
1
e = 7
e **= 2
49
/ always returns a float, // floors the result, % gives the remainder.0.== compares, = assigns; do not confuse them.and, or, and not combine and flip bool values.+= and friends are shorthand for "update this variable using its current value."Now that you know the operators themselves, here are a handful of details about how expressions actually behave, including a couple of common gotchas.
Parallel (or "tuple") assignment lets you assign several variables on one line. The names on the left line up, in order, with the values on the right.
You never have to use it, one variable per line always works, but it can be convenient.
Say x = 2 and y = 3, and we want to swap them. This does not work:
Once x = y runs, x's old value (2) is gone for good. There is nothing left to give y.
temp = x
x = y
y = temptemp briefly holds x's old value so it isn't lost.
x, y = y, xBoth right-hand values are read before either assignment happens.
Run the temp-variable version first. Then comment it out and try the one-line parallel swap instead. Both should print the same result.
To give the same value to multiple variables, you can chain assignments on one line.
x = y = 123 ** 45This assigns 123 ** 45 to both x and y.
Comparison operators can chain too, instead of writing it out with and.
(0 < i) and (i <= j)
# is the same as:
0 < i <= jNeither is required, but you should be able to read both.
+ means different things
The meaning of an operator can depend on the types of its values.
For numbers, + adds. For strings, + concatenates, joins them end to end.
* is even trickier* number: multiplies, as expected.* string: repeats the string that many times.* string: causes an error. Python has no idea what that would mean.Run this and read the error message for the last line. It names the exact types that don't get along, this is a very readable error once you know to look for it.
When an expression uses several operators, Python follows the same order you learned in math class.
( ), always first.**.* / // %.+ -.Within a level, Python works left to right, except **, which works right to left (rare to matter in practice).
1 + 2 * 31 + 2 * 3
Step 1: multiplication runs first, 2 * 3 → 6.
Step 2: 1 + 6 → 7.
5 - (4 + 8 % 3)?Work from the inside out: parentheses, then %, then +, then -.
-119-9
Like most languages, Python's float values can be off by a tiny, almost invisible amount.
== with floats
Run this. The second line prints False, even though 0.1 + 0.2 looks like it should equal 0.3.
== unreliable for floats. For now, just know the problem exists, later we'll meet a safer way to compare them.
An expression is anything that produces a value, anything that could go on the right-hand side of variable = expression. Literals, variables, function calls, and combinations of these with operators are all expressions.
A statement is a full action or command, like an assignment or a function definition.
print(x), a function call and therefore an expression, can stand alone as its own line of code.
You cannot simply break an expression across lines. Wrapping it in ( ) fixes that, and lets you format long expressions for clarity.
x = 12345 *
67890x = (12345 *
67890)Indent the continued line so it lines up just past the opening parenthesis.
9 // 3 ** 2 ** 0Remember: ** is right-to-left, so the rightmost ** goes first.
9 // 9 ** 03.0 ** 2 ** 03 ** 2 ** 09 // 3 ** 1A logic error is the sneakiest kind. Python understands your code, runs it start to finish, and never crashes. It does exactly the math you wrote, it's just not the math you meant.
The average of 4 and 8 should be 6. But / runs before +, so this actually computes a + (b / 2). The fix is parentheses: (a + b) / 2.
Predict each line before you reveal it. Hand-tracing catches logic errors that Python will never warn you about. It just does the math you told it to.
x, y = y, x can swap two variables.+ and * behave differently for numbers versus strings.**, then * / // %, then + -.==.