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()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")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)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
Catch what comes back in a variable.
def add(num1, num2):
return num1 + num2
total = add(3, 4)
print(total)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)}.")The area is 15.
Pass one answer into the next function
calc_tax() sends back the tax, and that value goes straight into calc_total().
def calc_tax(price, tax_percent):
return price * tax_percent / 100
def calc_total(price, tax, tip):
return price + tax + tip
price = 100
tax = calc_tax(price, 5.5)
total = calc_total(price, tax, 2.5)
print(f"Tax: ${tax}")
print(f"Total: ${total}")Tax: $5.5 Total: $108.0
A variable made inside stays inside
tax only exists while calc_tax() runs. Catch the returned value in a variable instead.
def calc_tax(price):
tax = price * 0.05
return tax
calc_tax(100)
print(tax)NameError: name 'tax' is not defined
Start everything from one place
Put all of your code inside functions, with a main() that starts everything. Each function gets what it needs from its parameters instead of reaching outside for it.
A main function
The last line calls main(). first_name goes in, and inside greet() it is called name. The names do not have to match.
def greet(name):
print(f"Hello there, {name}!")
def main():
first_name = "Steve"
greet(first_name)
main()Hello there, Steve!