Lesson 8: Functions and Parameters

How to organize reusable code using functions

What Are Functions?

Functions are reusable blocks of code that perform specific tasks. They help keep your programs organized, readable, and efficient.

Defining a Function

Use the def keyword to define a function:

def greet():
    print("Hello from a function!")

Calling a Function

Once defined, you call a function by using its name followed by parentheses:

greet()

Functions with Parameters

Parameters allow you to pass information into a function:

def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
greet("Bob")

Multiple Parameters

def add(a, b):
    return a + b

result = add(3, 5)
print(result)   # 8

Return Values

Functions can return values using the return statement:

def square(x):
    return x * x

print(square(4))   # 16

Default Parameter Values

You can assign default values to parameters:

def greet(name="friend"):
    print(f"Hello, {name}!")

greet()            # Hello, friend!
greet("Charlie")   # Hello, Charlie!

Keyword Arguments

Arguments can be passed by name:

def introduce(name, age):
    print(f"{name} is {age} years old.")

introduce(age=30, name="Alice")

Variable-Length Arguments

Use *args for multiple positional arguments:

def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3, 4))   # 10

Use **kwargs for multiple keyword arguments:

def show_info(**info):
    print(info)

show_info(name="Alice", age=30)

Why Functions Matter

Next Steps

Now that you understand functions, you’re ready to learn how Python organizes code into modules and packages in Lesson 9: Modules and Packages.

← Back to Lesson Index