Imagine you have a useful recipe that you want to use over and over again. Instead of writing out all the steps each time, you give the recipe a name and just refer to it when needed. Functions in Python work the same way - they let you package useful code with a name so you can use it repeatedly!
In this lesson, you'll learn:
def
A function is like a mini-program inside your program. You create it once and can use it many times. The basic pattern is:
def function_name(): # code to execute # notice the indentation!
The def
keyword tells Python "I'm defining a function." The colon :
at the end of the line introduces an indented block - all the code that belongs to the function must be indented 4 spaces.
# Define a simple function
def greet_user():
print("Hello there!")
print("Welcome to Python functions!")
# Call (use) the function
print("Before calling function")
greet_user()
print("After calling function")
# You can call it multiple times
greet_user()
greet_user()
Notice the indentation! Everything that belongs to the function must be indented the same amount (usually 4 spaces). Python uses this indentation to know what code is part of the function.
Create a function called show_info
that prints two lines of information about Python: Python is a programming language
and It was created by Guido van Rossum
. Call the function twice.
Functions become much more useful when you can pass information to them. These pieces of information are called parameters (when defining the function) or arguments (when calling the function).
Think of parameters as empty boxes that get filled with values when you call the function.
# Function with one parameter
def greet_person(name):
print("Hello,", name)
print("Nice to meet you!")
# Call with different arguments
greet_person("Alice")
greet_person("Bob")
greet_person("Maria")
Functions can have multiple parameters:
# Function with multiple parameters
def introduce_person(name, age, city):
print("This is", name)
print("They are", age, "years old")
print("They live in", city)
# Call with multiple arguments
introduce_person("Sarah", 25, "Denver")
introduce_person("Miguel", 30, "Austin")
Create a function called describe_book
that takes a title and page count as parameters, then prints information about the book.
So far our functions have only printed things. But functions can also return values - they can calculate something and give the result back to whoever called them. This makes functions much more powerful!
Use the return
keyword to send a value back from the function.
# Function that returns a value
def add_numbers(num1, num2):
result = num1 + num2
return result
# Save the returned value in a variable
sum1 = add_numbers(5, 3)
sum2 = add_numbers(10, 7)
print("First sum:", sum1)
print("Second sum:", sum2)
# You can use the return value directly
print("Double sum:", add_numbers(2, 4) * 2)
Functions can process and return text too:
# Function that processes text
def make_title(text):
title = "*** " + text + " ***"
return title
# Use the text processing function
book_title = make_title("Python Programming")
chapter_title = make_title("Functions")
print(book_title)
print(chapter_title)
When a function doesn't have a return
statement, it automatically returns None
. Functions that return values are often more useful because you can save the result and use it elsewhere in your program.
Create a function called calculate_area
that takes length and width parameters, calculates the area, and returns the result.
Variables created inside a function are called local variables. They only exist inside that function and disappear when the function finishes. This is like having a separate workspace for each function.
This prevents functions from accidentally interfering with each other!
# Variables outside functions (global)
message = "Global message"
number = 100
def process_data():
# Local variables - only exist inside this function
local_message = "Local message"
local_number = 42
print("Inside function:")
print("Local message:", local_message)
print("Local number:", local_number)
print("Global message:", message) # Can access global variables
print("Global number:", number)
# Call the function
process_data()
print("Outside function:")
print("Global message:", message)
print("Global number:", number)
# print(local_message) # This would cause an error!
Parameters are also local variables that exist only inside the function:
def calculate_average(score1, score2, score3):
# Parameters are also local variables
total = score1 + score2 + score3 # total is local
average = total / 3 # average is local
return average
result = calculate_average(85, 92, 78)
print("Average:", result)
# print(total) # This would cause an error - total doesn't exist here
Create a function called format_name
that takes first and last name parameters, creates a full name locally, and returns it.
Functions help organize your code by breaking complex tasks into smaller, manageable pieces. Each function should do one specific job well.
# Functions for mathematical calculations
def add_numbers(num1, num2):
return num1 + num2
def multiply_numbers(num1, num2):
return num1 * num2
def calculate_area(length, width):
area = length * width
return area
def calculate_total_cost(price, quantity, tax_rate):
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
return total
# Use the functions
print("Simple calculations:")
sum_result = add_numbers(15, 25)
product_result = multiply_numbers(7, 8)
print("15 + 25 =", sum_result)
print("7 × 8 =", product_result)
Here are some practical examples:
# Calculate room area
def calculate_area(length, width):
area = length * width
return area
room_area = calculate_area(12, 10)
print("Room area (12 × 10):", room_area, "square feet")
More complex calculations:
# Calculate shopping total
def calculate_total_cost(price, quantity, tax_rate):
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
return total
item_price = 29.99
item_quantity = 3
sales_tax = 0.08 # 8% tax
total_cost = calculate_total_cost(item_price, item_quantity, sales_tax)
print("Total cost for", item_quantity, "items at $", item_price, "each:", total_cost)
Create a function called calculate_average
that takes three numbers, adds them together, divides by 3, and returns the average.
When calling functions, you can specify which argument goes with which parameter by using the parameter name. This makes your code clearer and lets you put arguments in any order!
# Function with multiple parameters
def create_profile(name, age, city, hobby):
profile = name + " is " + str(age) + " years old, lives in " + city + ", and enjoys " + hobby + "."
return profile
# Positional arguments (order matters)
profile1 = create_profile("Alice", 25, "Boston", "reading")
print("Profile 1:", profile1)
# Keyword arguments (order doesn't matter)
profile2 = create_profile(hobby="painting", city="Seattle", name="Bob", age=30)
print("Profile 2:", profile2)
# Mix positional and keyword (positional must come first)
profile3 = create_profile("Carol", 28, city="Denver", hobby="hiking")
print("Profile 3:", profile3)
# Using keyword arguments makes code more readable
def calculate_tip(bill_amount, tip_percentage, split_ways):
tip = bill_amount * (tip_percentage / 100)
total = bill_amount + tip
per_person = total / split_ways
return per_person
# Clear which number means what
cost_per_person = calculate_tip(bill_amount=60.00, tip_percentage=18, split_ways=3)
print("Cost per person:", cost_per_person)
Create a function called book_info
that takes title, author, and year parameters. Call it using keyword arguments in a different order.
Let's create a comprehensive example that uses functions to build a text processing toolkit, combining all the concepts we've learned.
# Text Processing Toolkit using Functions
def word_count(text):
"""Count the number of words in the text."""
words = text.split()
return len(words)
def character_count(text, include_spaces=True):
"""Count characters, optionally excluding spaces."""
if include_spaces:
return len(text)
else:
return len(text.replace(" ", ""))
def sentence_count(text):
"""Count sentences by counting periods, exclamation marks, and question marks."""
periods = text.count(".")
exclamations = text.count("!")
questions = text.count("?")
return periods + exclamations + questions
def average_word_length(text):
"""Calculate the average length of words in the text."""
words = text.split()
if len(words) == 0:
return 0
total_length = 0
for word in words:
# Remove punctuation for more accurate measurement
clean_word = word.replace(".", "").replace(",", "").replace("!", "").replace("?", "")
total_length += len(clean_word)
return total_length / len(words)
def create_text_report(text, title="Text Analysis"):
"""Generate a comprehensive report about the text."""
words = word_count(text)
chars_with_spaces = character_count(text, include_spaces=True)
chars_without_spaces = character_count(text, include_spaces=False)
sentences = sentence_count(text)
avg_word_len = average_word_length(text)
# Build the report
report = "=" * 40 + "\n"
report += title + "\n"
report += "=" * 40 + "\n"
report += "Text: " + text + "\n\n"
report += "STATISTICS:\n"
report += "Words: " + str(words) + "\n"
report += "Characters (with spaces): " + str(chars_with_spaces) + "\n"
report += "Characters (without spaces): " + str(chars_without_spaces) + "\n"
report += "Sentences: " + str(sentences) + "\n"
report += "Average word length: " + str(round(avg_word_len, 2)) + " characters\n"
return report
# Test the toolkit
sample_text = "Python is amazing! It makes programming fun and accessible. Everyone should try it."
# Use individual functions
print("Word count:", word_count(sample_text))
print("Character count:", character_count(sample_text))
print("Sentence count:", sentence_count(sample_text))
print("Average word length:", round(average_word_length(sample_text), 2))
print()
# Use the comprehensive report function
full_report = create_text_report(sample_text, title="Python Text Analysis")
print(full_report)
Create a function called text_summary
that takes text as a parameter and returns a one-line summary with word count and character count.
Congratulations! You now know how to create and use functions in Python:
def function_name():
with indented code blockreturn
to send results backFunctions are one of the most important concepts in programming - they let you write code once and use it many times, making your programs more organized, readable, and maintainable!
Now that you can create reusable code with functions, you're ready to learn about making decisions in your code with conditional logic (if/elif/else statements)!