Function Basics: Defining and Calling Functions
Welcome to the foundation of reusable code! Functions are like recipes - you write them once and use them whenever you need.
What is a Function?
A function is a named block of code that performs a specific task. Itβs like a kitchen appliance:
- Input: Raw ingredients (parameters)
- Process: Cooking/mixing (function body)
- Output: Finished dish (return value)
Defining Your First Function
Basic Function Structure
def greet():
"""This is a docstring - it describes what the function does."""
print("Hello, World!")
print("Welcome to Python functions!")
# Call the function
greet()
greet() # You can call it multiple times!
Real-Life Example: Coffee Machine
def make_coffee():
"""Simulate making a cup of coffee."""
print("π Starting coffee machine...")
print("β Grinding coffee beans...")
print("π§ Adding hot water...")
print("β
Coffee is ready!")
print("Enjoy your coffee! β")
# Use the coffee machine
make_coffee()
print("--- Break time ---")
make_coffee() # Make another cup
Functions with Parameters
Single Parameter
def greet_person(name):
"""Greet a specific person."""
print(f"Hello, {name}!")
print(f"Nice to meet you, {name}!")
# Call with different names
greet_person("Alice")
greet_person("Bob")
greet_person("Charlie")
Multiple Parameters
def introduce_person(name, age, city):
"""Introduce a person with their details."""
print(f"My name is {name}.")
print(f"I am {age} years old.")
print(f"I live in {city}.")
# Call with multiple arguments
introduce_person("Alice", 25, "New York")
introduce_person("Bob", 30, "London")
Real-Life Example: Pizza Order
def order_pizza(size, topping1, topping2):
"""Place a pizza order."""
print(f"π Ordering a {size} pizza")
print(f"With {topping1} and {topping2}")
print("Your pizza will be ready in 20 minutes!")
print("-" * 40)
# Different pizza orders
order_pizza("large", "pepperoni", "mushrooms")
order_pizza("medium", "cheese", "olives")
order_pizza("small", "hawaiian", "extra cheese")
Return Values
Functions That Return Values
def calculate_square(number):
"""Calculate the square of a number."""
result = number * number
return result
# Use the returned value
square_of_5 = calculate_square(5)
print(f"5 squared is: {square_of_5}")
square_of_10 = calculate_square(10)
print(f"10 squared is: {square_of_10}")
# Use directly in expressions
total = calculate_square(3) + calculate_square(4)
print(f"3Β² + 4Β² = {total}")
Real-Life Example: Tax Calculator
def calculate_tax(price, tax_rate=0.08):
"""Calculate tax amount for a given price."""
tax_amount = price * tax_rate
return tax_amount
# Calculate tax for different items
laptop_price = 1000
laptop_tax = calculate_tax(laptop_price)
print(f"Laptop: ${laptop_price} + tax: ${laptop_tax:.2f} = ${laptop_price + laptop_tax:.2f}")
book_price = 20
book_tax = calculate_tax(book_price, 0.05) # Different tax rate
print(f"Book: ${book_price} + tax: ${book_tax:.2f} = ${book_price + book_tax:.2f}")
Default Parameters
Basic Default Parameters
def make_ice_cream(flavor, scoops=1):
"""Make ice cream with default 1 scoop."""
print(f"Making {scoops} scoop{'s' if scoops > 1 else ''} of {flavor} ice cream")
return f"{scoops} scoop{'s' if scoops > 1 else ''} of {flavor}"
# Use with default
single_scoop = make_ice_cream("vanilla")
print(single_scoop) # "1 scoop of vanilla"
# Override default
double_scoop = make_ice_cream("chocolate", 2)
print(double_scoop) # "2 scoops of chocolate"
Multiple Default Parameters
def send_email(to, subject, body="", priority="normal"):
"""Send an email with optional parameters."""
print(f"To: {to}")
print(f"Subject: {subject}")
print(f"Priority: {priority}")
if body:
print(f"Body: {body}")
print("π§ Email sent!")
print("-" * 40)
# Different email scenarios
send_email("boss@company.com", "Meeting Request")
send_email(
"friend@email.com",
"Party Invitation",
"Come to my party this Saturday!",
"high"
)
send_email("colleague@work.com", "Project Update", priority="low")
Variable Scope
Local Variables
def calculate_area():
"""Calculate area of a rectangle."""
# These are local variables - only exist inside the function
length = 5
width = 3
area = length * width
print(f"Inside function: area = {area}")
return area
# Call the function
result = calculate_area()
print(f"Outside function: result = {result}")
# Try to access local variables (this will cause an error)
# print(length) # NameError: name 'length' is not defined
Global Variables
# Global variable
total_score = 0
def add_points(points):
"""Add points to the global score."""
global total_score # Declare that we're using the global variable
total_score += points
print(f"Added {points} points. Total: {total_score}")
# Use the function
add_points(10)
add_points(20)
add_points(5)
print(f"Final score: {total_score}")
Best Practice: Avoid Global Variables
# β
Better approach: pass parameters and return values
def add_points(current_score, points):
"""Add points to a score."""
new_score = current_score + points
return new_score
# Usage
score = 0
score = add_points(score, 10)
score = add_points(score, 20)
score = add_points(score, 5)
print(f"Final score: {score}")
Function Examples
Example 1: Temperature Converter
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
# Test the converters
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")
# Check round-trip conversion
original_c = 30
converted_f = celsius_to_fahrenheit(original_c)
back_to_c = fahrenheit_to_celsius(converted_f)
print(f"Round-trip: {original_c}Β°C β {converted_f}Β°F β {back_to_c:.1f}Β°C")
Example 2: Simple Calculator
def add(x, y):
"""Add two numbers."""
return x + y
def subtract(x, y):
"""Subtract y from x."""
return x - y
def multiply(x, y):
"""Multiply two numbers."""
return x * y
def divide(x, y):
"""Divide x by y."""
if y == 0:
return "Error: Cannot divide by zero!"
return x / y
# Test the calculator functions
print("Calculator Test:")
print(f"5 + 3 = {add(5, 3)}")
print(f"10 - 4 = {subtract(10, 4)}")
print(f"6 * 7 = {multiply(6, 7)}")
print(f"15 / 3 = {divide(15, 3)}")
print(f"10 / 0 = {divide(10, 0)}")
Example 3: Text Formatter
def format_name(first_name, last_name, title=""):
"""Format a person's full name."""
if title:
full_name = f"{title} {first_name} {last_name}"
else:
full_name = f"{first_name} {last_name}"
return full_name
def create_greeting(name, time_of_day="morning"):
"""Create a personalized greeting."""
greeting = f"Good {time_of_day}, {name}!"
return greeting
# Test the text functions
person1 = format_name("John", "Doe", "Dr.")
greeting1 = create_greeting(person1, "afternoon")
print(greeting1)
person2 = format_name("Jane", "Smith")
greeting2 = create_greeting(person2)
print(greeting2)
Common Mistakes
1. Forgetting Parentheses When Calling
def say_hello():
print("Hello!")
# β Wrong - this just prints the function object
# say_hello
# β
Correct - this calls the function
say_hello()
2. Wrong Indentation
def my_function():
# β Wrong - missing indentation
print("This will cause an IndentationError")
def my_function():
# β
Correct - proper indentation
print("This works!")
3. Not Using Return Values
def calculate_total(price, tax_rate):
total = price + (price * tax_rate)
return total
price = 100
tax_rate = 0.08
# β Wrong - ignoring the return value
calculate_total(price, tax_rate)
print("Total: ???") # We don't know the total!
# β
Correct - using the return value
total = calculate_total(price, tax_rate)
print(f"Total: ${total}")
4. Confusing Parameters and Arguments
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!")
greet("Alice") # "Alice" is an argument
Practice Exercises
Exercise 1: Greeting Functions
Create functions that generate different types of greetings:
greet_casual(name)β βHey, Alice!βgreet_formal(name, title)β βGood morning, Dr. Smith!βgreet_time_based(name, hour)β Use hour to determine morning/afternoon/evening
Exercise 2: Math Functions
Create mathematical helper functions:
calculate_circle_area(radius)β Return area of circleis_even(number)β Return True if even, False if oddfind_max(a, b, c)β Return the largest of three numbers
Exercise 3: String Functions
Create string manipulation functions:
count_vowels(text)β Count vowels in a stringreverse_string(text)β Return reversed stringis_palindrome(text)β Check if string is palindrome
Exercise 4: Shopping Cart
Create shopping cart functions:
add_item(cart, item, price)β Add item to cart and return updated cartcalculate_total(cart)β Calculate total price of items in cartapply_discount(total, discount_percent)β Apply discount to total
Exercise 5: Temperature Tracker
Create a temperature tracking system:
record_temperature(temps, temp)β Add temperature to listget_average_temperature(temps)β Calculate averageget_highest_temperature(temps)β Find highest temperature
Summary
Functions are reusable blocks of code that make your programs organized and efficient:
- Define functions with
def function_name(parameters): - Call functions with
function_name(arguments) - Return values using the
returnstatement - Use default parameters for optional values
- Be careful with variable scope - local vs global
Key concepts:
- Functions help avoid code duplication
- Parameters make functions flexible
- Return values allow functions to communicate results
- Default parameters provide sensible defaults
- Local scope keeps variables contained
Next: Advanced Functions - parameters, args, and kwargs! β‘