Lesson 11 of 12
Functions 🔧
What You'll Learn
- Define and call functions
- Use parameters and return values
- Break a program into reusable pieces
What Is a Function?
A function is a reusable block of code you give a name. Instead of copying the same code in multiple places, you write it once as a function and call it whenever you need it.
Python
# Define the function
def greet():
print('Hello!')
print('Welcome to OKSTEM!')
# Call it as many times as you want
greet()
greet()Parameters and Arguments
Parameters are variables that receive data when the function is called:
Python
def greet(name):
print(f'Hello, {name}!')
greet('Alex') # Hello, Alex!
greet('Jordan') # Hello, Jordan!Return Values
Python
def add(a, b):
result = a + b
return result
total = add(5, 3)
print(total) # 8
print(add(10, 20)) # 30Return vs Print
A function that prints shows output but nothing comes back. A function that returns gives back a value you can use in more calculations.
Mini Calculator Functions
Write four functions: add(a, b), subtract(a, b), multiply(a, b), divide(a, b). Each should return the result. Then build a menu that asks which operation to use.
Quick Check
What keyword starts a function definition?
What does return do in a function?
What are the variables in the parentheses of a function definition called?