Functions in Python: How to Write, Use, and Reuse Code Like a Pro

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

Python
def greet():
    print("Hello! Welcome to PyUniverse.")
  • def starts the function
  • greet 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:

Python
greet()

Output:

Hello! Welcome to PyUniverse.


📥 Passing Data to Functions (Parameters)

Python
def greet_user(name):
    print(f"Hello, {name}! Welcome to PyUniverse.")

You can pass different names:

Python
greet_user("Ali")
greet_user("Fatima")

Output:

Hello, Ali! Welcome to PyUniverse.
Hello, Fatima! Welcome to PyUniverse.


🔢 Multiple Parameters

Python
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.

Python
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

Python
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

Python
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

Python
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:

Python
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:

Python
def profile(name, age):
    print(f"{name} is {age} years old.")

profile(age=25, name="Aamir")

⚙️ Functions That Call Other Functions

Python
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

Python
def print_line():
    print("-" * 30)

print("Shopping List")
print_line()
print("Milk\nEggs\nBread")
print_line()

🔍 Built-in vs User-Defined Functions

Built-inUser-Defined
print(), len(), type()def greet():, def add(a,b):
Already included in PythonYou write them yourself

⚠️ Common Mistakes

MistakeFix
Forgetting parenthesesCall functions with ()
Confusing print() vs returnUse return when you need to reuse the value
Wrong argument orderUse keyword arguments or match the parameter order
No indentationAlways indent function body (usually 4 spaces or 1 tab)

💌 Stay Updated with PyUniverse

Want Python and AI explained simply straight to your inbox?

Join hundreds of curious learners who get:

  • ✅ Practical Python tips & mini tutorials
  • ✅ New blog posts before anyone else
  • ✅ Downloadable cheat sheets & quick guides
  • ✅ Behind-the-scenes updates from PyUniverse

No spam. No noise. Just useful stuff that helps you grow one email at a time.

🛡️ I respect your privacy. You can unsubscribe anytime.

Leave a Comment