Module 3: Functions and modules · 10 min
Writing functions
A function is a named block of code. Define it with def, give it inputs (parameters) and send back an answer with return.
def average(numbers):
return sum(numbers) / len(numbers)
print(average([70, 80, 90])) # 80.0
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Sara")) # Hello, Sara!
print(greet("Sara", "Salam")) # Salam, Sara!
- Give functions short, clear verb names.
- One function should do one job.
- print shows something on screen; return gives a value back to the code that called the function. They are different.