# Define a simple function
def greet():
print("Hello, World!")
print("Welcome to Python functions!")
# Call (use) the function
greet()Hello, World!
Welcome to Python functions!
This tutorial will teach you how to write reusable blocks of code using functions in Python. By the end, you’ll understand how to create your own functions with parameters and return values, making your code more organized and efficient.
A function is a reusable block of code that performs a specific task. Think of it as a mini-program within your program!
Why use functions? - ✅ Reusability: Write code once, use it many times - ✅ Organization: Break complex problems into smaller pieces - ✅ Readability: Make code easier to understand - ✅ Maintainability: Fix bugs in one place instead of many
You’ve already been using built-in functions like print(), len(), type(), and input(). Now you’ll learn to create your own!
defUse the def keyword to define a function:
# Define a simple function
def greet():
print("Hello, World!")
print("Welcome to Python functions!")
# Call (use) the function
greet()Hello, World!
Welcome to Python functions!
Function Anatomy: 1. def - keyword to start a function definition 2. greet - the function name (use descriptive names!) 3. () - parentheses (we’ll add parameters here later) 4. : - colon to start the function body 5. Indented code - the code that runs when the function is called
To use a function, write its name followed by parentheses:
def say_hello():
print("Hello!")
# Call the function multiple times
say_hello()
say_hello()
say_hello()Hello!
Hello!
Hello!
Parameters allow you to pass information into a function. They make functions flexible and reusable with different values.
def greet_person(name):
print(f"Hello, {name}!")
print(f"Nice to meet you, {name}!")
# Call with different arguments
greet_person("Alice")
greet_person("Bob")
greet_person("Charlie")Hello, Alice!
Nice to meet you, Alice!
Hello, Bob!
Nice to meet you, Bob!
Hello, Charlie!
Nice to meet you, Charlie!
Terminology: - Parameter: The variable in the function definition (name) - Argument: The actual value you pass when calling ("Alice")
Functions can accept multiple parameters, separated by commas:
def introduce_person(name, age, city):
print(f"This is {name}.")
print(f"{name} is {age} years old.")
print(f"{name} lives in {city}.")
# Call with multiple arguments
introduce_person("Emma", 28, "New York")
print() # Blank line
introduce_person("Oliver", 35, "London")This is Emma.
Emma is 28 years old.
Emma lives in New York.
This is Oliver.
Oliver is 35 years old.
Oliver lives in London.
Arguments are matched to parameters by position:
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
# These give different results!
describe_pet("dog", "Buddy")
describe_pet("cat", "Whiskers")
# Order matters!
describe_pet("Fluffy", "hamster") # Swapped - doesn't make sense!I have a dog named Buddy.
I have a cat named Whiskers.
I have a Fluffy named hamster.
You can specify which parameter gets which value using keyword arguments:
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type} named {pet_name}.")
# Using keyword arguments - order doesn't matter!
describe_pet(pet_name="Max", animal_type="dog")
describe_pet(animal_type="cat", pet_name="Luna")I have a dog named Max.
I have a cat named Luna.
Give parameters default values that are used if no argument is provided:
def greet_user(name, greeting="Hello"):
print(f"{greeting}, {name}!")
# Use default greeting
greet_user("Alice")
# Override default greeting
greet_user("Bob", "Hi")
greet_user("Charlie", "Good morning")Hello, Alice!
Hi, Bob!
Good morning, Charlie!
Important: Parameters with default values must come after parameters without defaults:
# ✅ Correct - default parameter comes last
def make_pizza(size, topping="cheese"):
print(f"Making a {size}-inch {topping} pizza.")
make_pizza(12)
make_pizza(16, "pepperoni")Making a 12-inch cheese pizza.
Making a 16-inch pepperoni pizza.
The return statement sends a value back to the code that called the function.
def add_numbers(a, b):
result = a + b
return result
# The function returns a value we can use
sum1 = add_numbers(5, 3)
print(f"5 + 3 = {sum1}")
sum2 = add_numbers(10, 20)
print(f"10 + 20 = {sum2}")
# Use return value directly
print(f"100 + 50 = {add_numbers(100, 50)}")5 + 3 = 8
10 + 20 = 30
100 + 50 = 150
Important difference: - print() displays output to the screen - return sends a value back to be used in your code
# Function that prints (no return)
def print_sum(a, b):
print(a + b)
# Function that returns
def calculate_sum(a, b):
return a + b
# Compare the difference
print("Using print_sum:")
result1 = print_sum(5, 3)
print(f"Result stored: {result1}") # None!
print("\nUsing calculate_sum:")
result2 = calculate_sum(5, 3)
print(f"Result stored: {result2}") # 8Using print_sum:
8
Result stored: None
Using calculate_sum:
Result stored: 8
Functions can return any data type:
# Return a string
def create_full_name(first, last):
return first + " " + last
full_name = create_full_name("John", "Doe")
print(f"Full name: {full_name}")
# Return a boolean
def is_adult(age):
return age >= 18
print(f"Is 16 an adult? {is_adult(16)}")
print(f"Is 21 an adult? {is_adult(21)}")
# Return a float
def calculate_average(num1, num2, num3):
total = num1 + num2 + num3
average = total / 3
return average
avg = calculate_average(80, 90, 85)
print(f"Average: {avg}")Full name: John Doe
Is 16 an adult? False
Is 21 an adult? True
Average: 85.0
Python functions can return multiple values as a tuple:
def get_user_info():
name = "Alice"
age = 30
city = "Boston"
return name, age, city
# Unpack all values
user_name, user_age, user_city = get_user_info()
print(f"Name: {user_name}")
print(f"Age: {user_age}")
print(f"City: {user_city}")
# Or get as a tuple
user_info = get_user_info()
print(f"\nTuple: {user_info}")Name: Alice
Age: 30
City: Boston
Tuple: ('Alice', 30, 'Boston')
Functions can have multiple return statements. The function stops when it hits a return:
def check_age(age):
if age < 0:
return "Invalid age"
if age < 18:
return "Minor"
if age < 65:
return "Adult"
return "Senior"
print(check_age(-5))
print(check_age(16))
print(check_age(30))
print(check_age(70))Invalid age
Minor
Adult
Senior
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
celsius = (fahrenheit - 32) * 5/9
return celsius
# Use the functions
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f}°F")
temp_f2 = 77
temp_c2 = fahrenheit_to_celsius(temp_f2)
print(f"{temp_f2}°F = {temp_c2:.1f}°C")25°C = 77.0°F
77°F = 25.0°C
def calculate_rectangle_area(length, width):
"""Calculate the area of a rectangle."""
return length * width
def calculate_rectangle_perimeter(length, width):
"""Calculate the perimeter of a rectangle."""
return 2 * (length + width)
def describe_rectangle(length, width):
"""Display complete information about a rectangle."""
area = calculate_rectangle_area(length, width)
perimeter = calculate_rectangle_perimeter(length, width)
print(f"Rectangle: {length} × {width}")
print(f"Area: {area}")
print(f"Perimeter: {perimeter}")
# Use the functions
describe_rectangle(5, 3)Rectangle: 5 × 3
Area: 15
Perimeter: 16
def is_valid_password(password):
"""Check if a password is valid (at least 8 characters)."""
if len(password) >= 8:
return True
else:
return False
def validate_user(username, password):
"""Validate both username and password."""
if len(username) < 3:
return False, "Username too short"
if not is_valid_password(password):
return False, "Password must be at least 8 characters"
return True, "Valid credentials"
# Test the validator
is_valid, message = validate_user("john_doe", "secret123")
print(f"Valid: {is_valid}, Message: {message}")
is_valid, message = validate_user("jo", "pass")
print(f"Valid: {is_valid}, Message: {message}")Valid: True, Message: Valid credentials
Valid: False, Message: Username too short
Variables created inside a function are local - they only exist inside that function:
def my_function():
local_var = "I'm local!"
print(local_var)
my_function()
# This would cause an error:
# print(local_var) # NameError: local_var is not definedI'm local!
Variables created outside functions are global - accessible everywhere:
global_var = "I'm global!"
def my_function():
print(global_var) # Can access global variable
local_var = "I'm local!"
print(local_var)
my_function()
print(global_var) # Can access global variable
# print(local_var) # Would cause errorI'm global!
I'm local!
I'm global!
Use docstrings (triple quotes) to document what your function does:
def calculate_discount(price, discount_percent):
"""
Calculate the final price after applying a discount.
Parameters:
price (float): The original price
discount_percent (float): The discount percentage (0-100)
Returns:
float: The discounted price
"""
discount_amount = price * (discount_percent / 100)
final_price = price - discount_amount
return final_price
# Use the function
original = 100
discount = 20
final = calculate_discount(original, discount)
print(f"Original: ${original}")
print(f"Discount: {discount}%")
print(f"Final price: ${final}")
# Access the docstring
print(f"\nDocumentation:\n{calculate_discount.__doc__}")Original: $100
Discount: 20%
Final price: $80.0
Documentation:
Calculate the final price after applying a discount.
Parameters:
price (float): The original price
discount_percent (float): The discount percentage (0-100)
Returns:
float: The discounted price
Now it’s your turn! Try these exercises:
Write a function that takes a name and time of day, then prints a personalized greeting.
def greet_at_time(name, time_of_day):
# Your code here
pass
# Test it
greet_at_time("Alice", "morning") # Should print "Good morning, Alice!"
greet_at_time("Bob", "evening") # Should print "Good evening, Bob!"Write a function that calculates the area of a circle given its radius. Formula: Area = π × r² (use 3.14159 for π)
def calculate_circle_area(radius):
# Your code here
pass
# Test it
area = calculate_circle_area(5)
print(f"Area: {area}") # Should print approximately 78.54Write a function that takes three numbers and returns the largest one.
def find_max(a, b, c):
# Your code here
pass
# Test it
print(find_max(10, 25, 15)) # Should return 25
print(find_max(100, 50, 75)) # Should return 100Write a function that takes a string and returns it reversed.
def reverse_string(text):
# Your code here
pass
# Test it
print(reverse_string("Python")) # Should return "nohtyP"
print(reverse_string("Hello")) # Should return "olleH"Write a function that takes a number and returns “even” if it’s even, “odd” if it’s odd.
def even_or_odd(number):
# Your code here
pass
# Test it
print(even_or_odd(10)) # Should return "even"
print(even_or_odd(7)) # Should return "odd"Here are the solutions to the exercises:
def greet_at_time(name, time_of_day):
print(f"Good {time_of_day}, {name}!")
greet_at_time("Alice", "morning")
greet_at_time("Bob", "evening")Good morning, Alice!
Good evening, Bob!
def calculate_circle_area(radius):
pi = 3.14159
area = pi * radius ** 2
return area
area = calculate_circle_area(5)
print(f"Area: {area}")Area: 78.53975
def find_max(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
# Alternative solution using built-in max()
def find_max_simple(a, b, c):
return max(a, b, c)
print(find_max(10, 25, 15))
print(find_max(100, 50, 75))25
100
def reverse_string(text):
return text[::-1]
# Alternative solution using a loop
def reverse_string_loop(text):
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
return reversed_text
print(reverse_string("Python"))
print(reverse_string("Hello"))nohtyP
olleH
def even_or_odd(number):
if number % 2 == 0:
return "even"
else:
return "odd"
print(even_or_odd(10))
print(even_or_odd(7))even
odd
Short, one-line functions without a name:
# Regular function
def square(x):
return x ** 2
# Lambda function (does the same thing)
square_lambda = lambda x: x ** 2
print(square(5))
print(square_lambda(5))
# Common use: with map, filter, sorted
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared numbers: {squared}")25
25
Squared numbers: [1, 4, 9, 16, 25]
Accept any number of positional arguments:
def sum_all(*numbers):
"""Sum all provided numbers."""
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3))
print(sum_all(10, 20, 30, 40, 50))
print(sum_all(5))6
150
5
Accept any number of keyword arguments:
def print_info(**info):
"""Print all provided information."""
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="Boston")
print()
print_info(language="Python", version=3.9, is_fun=True)name: Alice
age: 30
city: Boston
language: Python
version: 3.9
is_fun: True
✨ Remember: 1. Use def to create functions 2. Parameters allow functions to accept input 3. Use return to send values back from functions 4. Default parameters provide fallback values 5. Functions make code reusable and organized 6. Document functions with docstrings 7. Variables inside functions are local to that function 8. return is different from print() - return gives you a value to use
📝 Tips for writing good functions: - Give functions descriptive names (use verbs: calculate_, get_, create_) - Keep functions focused on one task - Use parameters instead of global variables - Return values rather than printing when possible - Add docstrings to explain complex functions - Use default parameters for optional values - Keep functions short and simple (generally under 20 lines)
Now that you understand functions, you’re ready to learn: - Lists and list comprehensions - Dictionaries and data structures - File handling - Object-oriented programming (classes) - Error handling (try/except) - Modules and imports
Keep practicing by breaking your code into small, reusable functions! 🚀