Skip to main content

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​

Quiz

def and return

1 / 2

What does this print?

def f():
return 2
print(f() + 3)

Pick an answer to see if you are right.


Challenge: double​

Write double(n) so it returns twice n.

nReturn
48
-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​

Quiz

Defaults and scope

1 / 2

What 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.

nlowhighReturn
5110True
0110False

Exercises​

Activity: Count vowels

Write count_vowels(text) so it returns how many characters are in aeiouAEIOU.

Expected for Hello:

2