šŸ

Functions: Reusable Code Blocks

Beginner
90 XP
40 min
Lesson Content

Functions: Write Once, Use Many Times

Functions are reusable blocks of code that perform specific tasks. They help organize code, avoid repetition, and make programs easier to understand and maintain.

Defining Functions

Use the def keyword to define a function:

# Simple function
def greet():
print("Hello, World!")
# Call the function
greet() # Prints: Hello, World!

Functions with Parameters

Functions can accept input values (parameters):

# Function with one parameter
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Prints: Hello, Alice!
# Function with multiple parameters
def add(a, b):
return a + b
result = add(5, 3) # result = 8
print(result)

The return Statement

Functions can return values using return:

# Function that returns a value
def multiply(x, y):
return x * y
product = multiply(4, 5) # product = 20
print(product)
# Function without return (returns None)
def print_message(msg):
print(msg)
result = print_message("Hi") # result = None

Default Parameters

Provide default values for parameters:

def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice! greet("Bob", "Hi") # Hi, Bob!

Multiple Return Values

Functions can return multiple values:

def get_name_and_age():
name = "Alice"
age = 25
return name, age # Returns a tuple
name, age = get_name_and_age()
print(f"{name} is {age} years old")

Variable Scope

Variables have different scopes:

# Global variable
x = 10 def my_function(): # Local variable y = 5 print(x) # Can access global x print(y) # Can access local y my_function() print(x) # Can access global x # print(y) # Error! y is local to function

Common Function Patterns

# Calculate area of rectangle
def rectangle_area(length, width):
return length * width area = rectangle_area(5, 3) # 15 # Check if number is even
def is_even(number):
return number % 2 == 0 print(is_even(4)) # True print(is_even(5)) # False

Why Use Functions?

  • āœ… Reusability: Write once, use many times
  • āœ… Organization: Break code into logical pieces
  • āœ… Maintainability: Easier to update and debug
  • āœ… Readability: Code is easier to understand
Example Code

Create functions to perform common calculations.

# Create a function that calculates the area of a circle
# Formula: area = Ļ€ * radius²
# Use 3.14159 for π

def circle_area(radius):
    pi = 3.14159
    return pi * radius * radius

# Test the function
result = circle_area(5)
print(f"Area of circle with radius 5: {result}")

Expected Output:

Area of circle with radius 5: 78.53975
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code