Beginner-Friendly Topic
Take your time — it's perfectly normal to re-read this topic 2–3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Defining & Calling Functions
Functions are reusable blocks of code that perform a specific task. They help you organize code, avoid repetition, and make programs more readable. Use the def keyword to define a function.
Function Basics
# Defining a function
def greet():
print("Hello, World!")
# Calling a function
greet() # Hello, World!
greet() # Can call multiple times!
# Function with parameter
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Alice") # Hello, Alice!
greet_user("Bob") # Hello, Bob!
# Function with multiple parameters
def add(a, b):
result = a + b
print(f"{a} + {b} = {result}")
add(5, 3) # 5 + 3 = 8
add(10, 20) # 10 + 20 = 30Tip
Tip
Functions should do ONE thing. If your function name has 'and' in it, it's doing too much. Split it into smaller functions.
Functions are first-class objects in Python — pass them, return them, store them
Common Mistake
Warning
Defining a function but forgetting to call it. def greet(): creates it but doesn't run it. You must call greet() separately.
Practice Task
Note
(1) Write a greet(name) function. (2) Write an add(a, b) that returns the sum. (3) Call each function 3 times with different arguments.