Functions
A function is a named, reusable block of code. Anywhere you find yourself writing similar code more than once, that's usually a sign it should be a function instead.
main.py
Try it yourself →def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
print(greet("Bob"))Output
Hello, Alice! Hello, Bob!
- def starts a function definition, followed by its name and parameters in parentheses
- return sends a value back to wherever the function was called — without it, a function returns None
- name is a parameter — a placeholder that gets filled in with whatever you pass when you call the function
Default arguments
You can give a parameter a default value, making it optional — callers can leave it out entirely, or override it when they need something different.
main.py
Try it yourself →def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice"))
print(greet("Bob", "Hi"))Output
Hello, Alice! Hi, Bob!
Next: lambda functions — small, throwaway functions written in a single line.
Practice exercise
Write a function square(n) that returns n * n, then print square(6).