In Python, functions let you package code into reusable blocks. Instead of rewriting the same logic again and again, you can define a function once and call it whenever you need. This makes your code cleaner, easier to read, and much more efficient.
Defining and Calling Functions
def greet():
print("Hello from a function!")
# Call the function
greet()
A function starts with the keyword def, followed by the function’s name, parentheses, and a colon. The indented block underneath is the function body — the code that runs when you call it.
Functions with Parameters
Parameters let you make functions more flexible by passing in values.
def greet_user(name):
print(f"Hello, {name}!")
greet_user("Tyler")
greet_user("Maya")
Here, name is a parameter. When you call the function, you provide an argument (like “Tyler”) that gets used inside.
Returning Values
Sometimes you don’t just want to print inside a function — you want it to give something back. That’s where return comes in.
def square(number):
return number * number
result = square(4)
print(result) # 16
The return keyword sends data back to the caller, allowing you to use it elsewhere in your program.
Interactive Exercise: Define and Use Functions
Try writing your own functions! Start with a basic one, then expand it with parameters and return values. Experiment by adding more calls and new arguments.
# 1. Define a simple function
def greet():
print("Welcome to Python functions!")
greet()
# 2. Define a function with a parameter
def repeat_message(msg, times):
for i in range(times):
print(msg)
repeat_message("Practice makes perfect", 3)
# 3. Define a function that returns a value
def add(a, b):
return a + b
total = add(10, 5)
print("Sum:", total)
# Try adding:
# - A function that multiplies two numbers
# - A function that takes a list and prints each item
def, give your function a name, and indent the code block.return when you want the function to give back a result instead of just printing.Functions are one of the most powerful features in Python. By breaking your programs into smaller, reusable pieces, you’ll be able to write cleaner, more flexible code that’s easier to debug and maintain.