Chapter 9a - Functions
A function is a named block you can call. def defines it. return sends a value back to the caller.
def greet(name):
return "Hello, " + name
print(greet("Ada"))
π§ͺ Try it yourself
Add a second function that returns n * 10.
Parameters and returnβ
Arguments fill parameters when you call the function. If you print inside the function, that is a side effect. Prefer return when you need a value for later math or tests.
def add(a, b):
return a + b
total = add(3, 5)
print(total)
π§ͺ Two parameters
Mini quiz β def and returnβ
def and return
1 / 2What does this print?
def f():return 2print(f() + 3)
Pick an answer to see if you are right.
Challenge: doubleβ
Write double(n) so it returns twice n.
| n | Return |
|---|---|
4 | 8 |
-3 | -6 |
Default arguments and local variablesβ
def greet(name, punctuation="!"):
return "Hi " + name + punctuation
print(greet("Lin"))
print(greet("Lin", "?"))
Variables created inside a function are local. They disappear when the function ends.
π§ͺ Defaults
Mini quiz β defaults and scopeβ
Defaults and scope
1 / 2What is greet("Ada")?
def greet(name, p="!"):return name + p
Pick an answer to see if you are right.
Challenge: in rangeβ
Write in_range(n, low, high) so it returns True if n is between low and high inclusive, otherwise False.
| n | low | high | Return |
|---|---|---|---|
| 5 | 1 | 10 | True |
| 0 | 1 | 10 | False |
Exercisesβ
Write count_vowels(text) so it returns how many characters are in aeiouAEIOU.
Expected for Hello:
2