We define functions in Python with a def
statement.
def <name>(<parameters>):
return <return expression>
Example:
def add(num1, num2): # ← Function signature
sum = num1 + num2 # ← Function body
return sum # ← Function body
Once defined, we can call it:
add(2, 2)
add(18, 69)
We can pass in any expressions as arguments.
def add(num1, num2):
return num1 + num2
x = 1
y = 2
add(x, y)
x = 3
add(x * x, x + x)
The return keyword returns a value to whoever calls the function (and exits the function).
def add(num1, num2):
return num1 + num2
sum = add(2, 4)
Python uses the concept of namespaces to organize the symbolic names assigned to objects, like variables and functions. Namespaces help to avoid name conflicts.
Python has 4 levels of namespaces:
Built-in | Contains the names of all of Python’s built-in objects (ex, functions like print() and pow()) |
Global | Contains any names defined at the level of the main program (ie, variable & function names that are NOT indented) |
Enclosing | When functions are nested, contains names defined inside a parent function (ie, variabl & function names that are indented) |
Local | Contains names defined inside a function (ie, variable names that are indented) |
In practice, we mostly care about whether a name is global or local.
Global | ![]() |
Local | ![]() |
A side effect is when something happens as a result of calling a function besides just returning a value.
The most common side effect is logging to the console, via the built-in print()
function.
print(-2)
A similar side effect is writing to a file:
f = open('songs.txt', 'w')
f.write("Dancing On My Own, Robyn")
f.close()
def square_num1(number):
return pow(number, 2)
def square_num2(number):
print(number ** 2)
In the function signature, a parameter can specify a default value. If that argument isn't passed in, the default value is used instead.
def calculate_dog_age(human_years, multiplier = 7):
return human_years * multiplier
These two lines of code have the same result:
calculate_dog_age(3)
calculate_dog_age(3, 7)
Default arguments can be overriden:
calculate_dog_age(3, 6)
A function can specify multiple return values, separated by commas.
def divide_exact(n, d):
quotient = n // d
remainder = n % d
return quotient, remainder
Any code that calls that function must also "unpack it" using commas:
q, r = divide_exact(618, 10)
Let's review the homework from last week together!
(Note: we did Class2Ex2TemperatureConverter together in class)
A Boolean value is either True
or False
and is used frequently in computer programs.
Google Maps uses a boolean to decide whether to avoid highways in driving directions:
avoid_highways = True
Twitter uses a boolean to remember where the user allows personalized ads:
personalized_ads = False
An expression can evaluate to a Boolean. Most Boolean expressions use either comparison or logical operators.
An expression with a comparison operator:
passed_class = grade > 65
An expression with a logical operator:
wear_jacket = is_raining or is_windy
Let's try it in Replit . Create a new Python 3 Repl.
Operator | Meaning | True expressions |
== | Equality | 32 == 32 , "foo" == "foo"
|
!= | Inequality | 30 != 32 , "foo" != "bar"
|
> | Greater than | 60 >= 32
|
>= | Greater than or equal | 60 >= 32 , 32 >= 32
|
< | Less than | 20 < 32
|
<= | Less than or equal | 20 <= 32 , 32 <= 32
|
⚠️ Common mistake: Do not confuse =
(the assignment operator) with ==
(the equality operator).
x = y
is very different from
x == y
Operator | True expressions | Meaning |
---|---|---|
and | 4 > 0 and -2 < 0 | True if both conditions are true; otherwise evaluates to False . Same as && in other languages.
|
or | 4 > 0 or -2 > 0 | True if either condition is true; evaluates to False only if both are false. Same as || in other languages.
|
not | not (5 == 0) | True if condition is false; evaluates to False if condition is true. Same as ! in other languages.
|
W3Schools has a handy Python operators reference
You might recognize logical operators from Advanced Search tools, like in Google Advanced Search
When combining multiple operators in a single expression, use parentheses to group:
may_have_mobility_issues = (age >= 0 and age < 2) or age > 90
A function can use a Boolean expression to return a result based on the values of the parameters.
def passed_class(grade):
return grade > 65
def should_wear_jacket(is_rainy, is_windy):
return is_rainy or is_windy
Open Class3Ex1Booleans in Replit and click "Fork Repl" to create your own copy
We'll do the first question together; the rest will be homework for the next class.
A conditional statement gives you a way to execute a different set of code statements based on whether certain conditions are true or false.
if <condition>:
<statement>
<statement>
...
A simple conditional:
clothing = "shirt"
if temperature < 32:
clothing = "jacket"
In what situations will clothing
be assigned to "jacket"?
A conditional can include an else
statement
to specify code to execute when the if
condition is False
if <condition>:
<statement>
else <condition>:
<statement>
if temperature < 0:
clothing = "snowsuit"
else:
clothing = "jacket"
When you have more than 1 condition you want to check, you can use elif
statements to check other conditions. Works kind of like a "choose your own adventure" book!
if <condition>:
<statement>
...
elif <condition>:
<statement>
...
elif <condition>:
<statement>
...
clothing = "shirt"
if temperature < 0:
clothing = "snowsuit"
elif temperature < 32:
clothing = "jacket"
else
can be used along with 1 or more elif
statements
to specify code to execute as a last resort, if no previous conditions are true.
if <condition>:
<statement>
...
elif <condition>:
<statement>
...
else <condition>:
<statement>
...
if temperature < 0:
clothing = "snowsuit"
elif temperature < 32:
clothing = "jacket"
else:
clothing = "shirt"
clothing = "shirt"
if temperature < 0:
clothing = "snowsuit"
elif temperature < 32:
clothing = "jacket"
else:
clothing = "shirt"
temperature | clothing
|
---|---|
-50 | snowsuit |
-1 | snowsuit |
0 | jacket |
1 | jacket |
31 | jacket |
32 | shirt |
50 | shirt |
if num < 0:
sign = "negative"
elif num > 0:
sign = "positive"
else:
sign = "neutral"
Syntax tips:
if
clause.
elif
clauses.
else
clause, always at the end.
How Python interprets a conditional:
It's common for a conditional to be based on the value of the parameters to a function.
def get_number_sign(num):
if num < 0:
sign = "negative"
elif num > 0:
sign = "positive"
else:
sign = "neutral"
return sign
get_number_sign(50) # "positive"
get_number_sign(-1) # "negative"
get_number_sign(0) # "neutral"
A branch of a conditional can end in a return, which exits the function entirely.
def get_number_sign(num):
if num < 0:
return "negative"
elif num > 0:
return "positive"
else:
return "neutral"
get_number_sign(50) # "positive"
get_number_sign(-1) # "negative"
get_number_sign(0) # "neutral"
We'll do the first question together; the rest will be homework for the next class
Sometimes we need to do the same thing over and over, with different data.
Consider the following code...
print(9 * 1)
print(9 * 2)
print(9 * 3)
print(9 * 4)
print(9 * 5)
This code is repetitive and variable, but the variability is sequential - it just adds one to the right-hand side number each time. In English, we could describe this as "print out the first 5 multiples of 9".
We can simplify this code with a loop!
Python has 2 types of loops:
The while loop syntax:
while <condition>:
<statement>
<statement>
As long as the condition is true, the statements below it are executed.
multiplier = 1
while multiplier <= 5:
print(9 * multiplier)
multiplier += 1
The code is significantly shorter, and it can easily be extended to loop for more or less iterations.
We need to tell a While loop when to stop, otherwise it might keep running forever!
It's common to use a counter variable whose job is keeping track of the number of times the loop has run.
total = 0
counter = 0
while counter < 5:
total += pow(2, 1)
counter += 1
What's this +=
thing?
counter += 1
does the same thing as counter = counter + 1
Can also subtract -=
, multiply *=
, divide /=
and assign the result
See the full list of special assignment operators on W3Schools
How many times will this loop run?
total = 0
counter = 0
while counter < 5:
total += pow(2, 1)
counter += 1
The loop runs while counter is 0, 1, 2, 3 and 4, so 5 times
You can change the initial values of the variables used in the condition:
multiplier = 3
while multiplier <= 5:
print(9 * multiplier)
multiplier += 1
You can change the condition:
multiplier = 3
while multiplier <= 10:
print(9 * multiplier)
multiplier += 1
You can change how much the values change between iterations:
multiplier = 3
while multiplier <= 10:
print(9 * multiplier)
multiplier += 2
Uh oh..
counter = 1
while counter < 5:
total += pow(2, counter)
What one line of code would fix this?
counter += 1
counter = 6
while counter > 5:
total += pow(2, counter)
counter += 1
How do we save this code?
Intentions are unclear! Change the initial value and condition?
To prematurely exit a loop, use the break
statement:
counter = 100
while counter < 200:
if counter % 7 == 0:
first_multiple = counter
break
counter += 1
A loop in a function will commonly use a parameter to determine some aspect of its repetition.
def sum_up_squares(start, end):
counter = start
total = 0
while counter <= end:
total += pow(counter, 2)
counter += 1
return total
sum_up_squares(1, 5)
We'll do the first question together; the rest will be homework for the next class
Finish the rest of the questions in each exercise - we'll review in the next class
Please fill out the feedback form to let me know how I can improve the class!