⚙️
Python Functions
Reusable blocks of code with def
Reward
+70 XP
Defining functions
Use the def keyword followed by the function name and parentheses.
def greet(name):
print(f"Hello, {name}!")
greet("Alice")Return values
Use return to send a value back from the function.
def add(a, b):
return a + b
result = add(3, 4)
print(result) # 7Default parameters
Give parameters default values that can be overridden.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice")
greet("Bob", "Hi")Try it yourself
Run the example below. Edit it and see what changes.
main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)
Common mistakes
- ⚠Forgetting the colon after def and the parentheses.
- ⚠Forgetting to return a value — the function returns None by default.
- ⚠Mutable default arguments (like lists) are shared between calls.
