Functions
Name a chunk of code so you can reuse it.
Define it, then call it
Writing def only teaches Python the steps. Nothing runs until you call it.
A function with no inputs
Define it with def, then call it by name with ().
def invalid_login():
print("Your login information is incorrect.")
print("Please try again.")
invalid_login()Output
Your login information is incorrect. Please try again.
Calling it more than once
Write it once, use it as often as you want.
def greet(name):
print(f"Hi, {name}!")
greet("Becca")
greet("Steve")Output
Hi, Becca! Hi, Steve!
Pass values in
Parameters
The values in the call fill the names in the def, in order.
def add(num1, num2):
total = num1 + num2
print(f"{num1} + {num2} = {total}")
add(3, 4)
add(-8, 20)Output
3 + 4 = 7 -8 + 20 = 12
Send a value back
return hands a value back to whoever called it. It does not print anything.
Returning a value
Use this oneCatch what comes back in a variable.
def add(num1, num2):
return num1 + num2
total = add(3, 4)
print(total)Output
7
Using the value right away
You can drop the call straight into an f-string.
def area(width, height):
return width * height
print(f"The area is {area(3, 5)}.")Output
The area is 15.