00 Intro
00 Intro
1 Python as a calculator
Let’s start with some basic operators:
Q. With 8 % 3 we get the remainder from “long division”, but 8 / 3 doesn’t give us the long-
division quotient. How do we get the quotient?
A.
Q. What happens when we try to evaluate an expression that can’t work (e.g., 4 / 0)?
A.
2 Python types
Let’s use Python’s function type to find out the types of the numbers we’ve been working with:
There are also functions that take a value of one type and “convert” it to another:
1
3 Variables
A variable in Python is a name of some value.
p = 5
q = p * 7
Equality vs assignment:
• In math, p = q + 10 states a fact about the value of p and of q + 10: that they are equal.
• Programming languages usually have different symbols for assignment and equality. In
Python, the symbol for equality is ==
2
• In math, these are inconsistent:
p = 5
q = 7
p = q + 10
• You can change a variable’s value as many times as you want. You can change it to a value
of a different type, too.
In mathematics, equations are descriptions that are simultaneously true. In Python, assign-
ment statements look like equations but really specify a sequence of steps.
• Assignment is not symmetric
math Python
sum = a + b legal
same meaning
a + b = sum illegal
Observation:
• What does this do?
– x = 37
– y = x + 2 # y is now 39
– x = 20 # Is y now 22?
• That’s not how assignment works!
3
4 Functions
4.1 Motivation
Q. Consider a cookbook with 12 cake recipes, 3 of them involving a butter-cream frosting. We
could repeat that part of the recipe 3 times. What is a better option?
A.
function name(arguments)
4
4.4 Nested function calls
The distinction in Python is complex. In this course, you can think of it as follows: