Functions in Python
1 min read3 lessons in topic
Learning objective
By the end of this lesson you will be able to define functions with parameters and return values.
Functions bundle a piece of logic under a name so you can reuse it without copying code.
Defining a function
def greet():
print("Hello!")
greet() # Hello!Parameters
def greet(name):
print("Hello,", name)
greet("Ama") # Hello, AmaReturn values
def area(length, width):
return length * width
result = area(5, 3)
print(result) # 15Default arguments
def greet(name, greeting="Hello"):
print(greeting + ", " + name)
greet("Kofi") # Hello, Kofi
greet("Kofi", "Good day") # Good day, Kofi- def — declares a function
- Parameters are the values passed in
- return sends a value back to the caller
- Call a function with name(args)
Code playground
Run and edit the starter code — experiment freely.
python · runnable
Output appears here when you press Run.
Practice exercise
Write a function rectangle_area(length, width) and use it to print the area of a 7 × 4 rectangle.
Check your understanding
1. Which keyword defines a function in Python?
2. What happens when a function reaches return?
Self-graded — answer then check below.