Imagine writing a piece of code once and using it over and over again without copying and pasting.
That’s the power of functions.
In this lesson, you’ll learn:
- What functions are and why they matter
- How to write custom functions
- How to pass data (arguments) into functions
- How to get data out (return values)
- The difference between built-in vs user-defined functions
- How to write clean, reusable, readable code using functions
Let’s go step by step, with tons of examples.
🧠 What Is a Function?
A function is a reusable block of code that does something.
You define it once, and then call it whenever you need it.
Think of it like a blender:
- You give it ingredients (inputs)
- It processes them
- And returns a smoothie (output)
✅ How to Define a Function
def greet():
print("Hello! Welcome to PyUniverse.")
def
starts the functiongreet
is the function name()
holds parameters (more on that later)- Indented block is what the function does
📞 Calling a Function
Once defined, you call the function by its name:
greet()
Output:
Hello! Welcome to PyUniverse.
📥 Passing Data to Functions (Parameters)
def greet_user(name):
print(f"Hello, {name}! Welcome to PyUniverse.")
You can pass different names:
greet_user("Ali")
greet_user("Fatima")
Output:
Hello, Ali! Welcome to PyUniverse.
Hello, Fatima! Welcome to PyUniverse.
🔢 Multiple Parameters
def add(a, b):
print("Sum:", a + b)
add(5, 3)
add(100, 20)
Output:
Sum: 8
Sum: 120
📤 Returning Data from Functions
Functions don’t have to just print they can return a result.
def multiply(x, y):
return x * y
result = multiply(4, 6)
print("Product is:", result)
Output:
Product is: 24
return
sends the result back to wherever the function was called.
🧩 Example: BMI Calculator
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
return round(bmi, 2)
my_bmi = calculate_bmi(68, 1.75)
print("Your BMI is:", my_bmi)
🚫 Return vs Print
def say_hello():
return "Hello"
x = say_hello()
print(x)
return
gives you a value you can reuse.print()
just displays something on screen it doesn’t store anything.
🧪 Real Use: Age Check
def is_adult(age):
return age >= 18
print(is_adult(21)) # True
print(is_adult(16)) # False
🧠 Default Arguments
You can assign default values to parameters:
def greet(name="Guest"):
print(f"Hi, {name}!")
greet("Sara")
greet()
Output:
Hi, Sara!
Hi, Guest!
💡 Keyword Arguments
Order doesn’t matter when you use names:
def profile(name, age):
print(f"{name} is {age} years old.")
profile(age=25, name="Aamir")
⚙️ Functions That Call Other Functions
def square(x):
return x * x
def print_square(x):
result = square(x)
print(f"The square of {x} is {result}")
print_square(7)
🔁 Reusability in Action
def print_line():
print("-" * 30)
print("Shopping List")
print_line()
print("Milk\nEggs\nBread")
print_line()
🔍 Built-in vs User-Defined Functions
Built-in | User-Defined |
---|---|
print() , len() , type() | def greet(): , def add(a,b): |
Already included in Python | You write them yourself |
⚠️ Common Mistakes
Mistake | Fix |
---|---|
Forgetting parentheses | Call functions with () |
Confusing print() vs return | Use return when you need to reuse the value |
Wrong argument order | Use keyword arguments or match the parameter order |
No indentation | Always indent function body (usually 4 spaces or 1 tab) |