Welcome to Day 12 of the 100 Days of Python series!
Today, we’re introducing functions — reusable blocks of code that make your programs modular, readable, and easier to debug.
By the end of this article, you'll understand how to define, call, and use parameters in functions, as well as return values using the return
statement.
📦 What You’ll Learn
- What a function is and why it's useful
- How to define a function with
def
- How to pass data using parameters
- How to get results using
return
- Real-world examples of functions in action
🧠 What Is a Function?
A function is a block of code that only runs when you call it. It can take inputs (parameters), do some work, and optionally return a result.
Think of it as a machine: you give it something, it processes it, and gives something back.
🔧 1. Defining a Function with def
You define a function using the def
keyword:
def greet():
print("Hello from a function!")
To call the function, use its name followed by parentheses:
greet()
Output:
Hello from a function!
📨 2. Adding Parameters
Parameters let you pass data into functions.
def greet_user(name):
print(f"Hello, {name}!")
Call it with an argument:
greet_user("Alice") # Output: Hello, Alice!
You can pass multiple parameters:
def add(x, y):
print(x + y)
add(5, 3) # Output: 8
🎯 3. Returning Values with return
Use return
to send a result back to the caller.
def square(number):
return number * number
result = square(4)
print(result) # Output: 16
You can return:
- A single value
- Multiple values as a tuple
- Even other data types like lists, dicts, etc.
✨ Example: Calculator Functions
def add(x, y):
return x + y
def subtract(x, y):
return x - y
print(add(10, 5)) # 15
print(subtract(10, 5)) # 5
🚀 Real-World Example 1: Tip Calculator
def calculate_tip(amount, percent):
tip = amount * (percent / 100)
return round(tip, 2)
print("Tip:", calculate_tip(200, 10)) # Tip: 20.0
🧪 Real-World Example 2: Check Even or Odd
def is_even(number):
return number % 2 == 0
print(is_even(6)) # True
print(is_even(7)) # False
📌 Default Parameters
You can assign default values to parameters:
def greet(name="stranger"):
print(f"Hello, {name}!")
greet() # Hello, stranger!
greet("Maria") # Hello, Maria!
⚠️ Common Mistakes
- Forgetting to call the function with
()
- Not returning a value when you expect one
- Confusing parameters (placeholders in the function) with arguments (actual values you pass)
🧠 Recap
Today you learned:
- How to define a function using
def
- How to use parameters to pass data
- How to use
return
to get a result - Real-world examples: calculators, checkers, greeting users
Top comments (0)