Codeskill

Learn to code, step by step

Functions in Python: Reusing Code Effectively

How to define them, pass arguments, return values, and reuse code instead of copying it.

What are functions?

A function is a named block of code that does one job. You give it input, it does something, and often gives back a result. Functions break big problems into smaller pieces and stop you repeating yourself.

Defining a function

Start with def, then the function name and parentheses. Parameters go inside the parentheses:

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

greet is the function name. name is the parameter it expects.

Calling a function

Use the function by name and pass in the values it needs:

greet("Alice")

Outputs: Hello, Alice!

Return values

return sends a value back to whoever called the function:

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

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

Default arguments

You can give parameters a default value. If the caller does not supply one, the default is used:

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

greet("Bob")          # Outputs: Hello, Bob!
greet("Bob", "Hi")    # Outputs: Hi, Bob!

Keyword arguments

When calling a function, you can name the arguments explicitly. Makes code easier to read, especially with several parameters:

def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet(animal_type="hamster", pet_name="Harry")

Arbitrary number of arguments

Sometimes you do not know how many arguments a function will receive. Prefix a parameter with * to collect extra arguments into a tuple:

def make_pizza(*toppings):
    print("Making a pizza with the following toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

Using functions as building blocks

Small functions that each do one thing can be combined into larger ones. Write the pieces first, then wire them together.

Scope of variables in functions

Variables created inside a function are local to that function. They do not exist outside it. If you need the result elsewhere, return it with return.

Docstrings

Document your functions with a docstring – a triple-quoted string right after the function header:

def add(a, b):
    """Return the sum of two numbers a and b."""
    return a + b

Functions keep code organised and DRY (Don’t Repeat Yourself). Start pulling repeated logic into functions early – it pays off quickly as programs grow.

PreviousControl the Flow: Understanding If-Else and Loops in Python