🐍

Defining and Calling Functions

Programare Python Intermediate 5 min read

Defining and Calling Functions

What is a Function?

A function is a reusable code block that performs a specific task. Functions help with:

  • Code reuse
  • Program organization
  • Avoiding repetition (DRY - Don’t Repeat Yourself)

Defining a Function

def function_name():
    # function body
    statements

Simple example:

def greet():
    print("Hello, world!")

# Calling the function
greet()  # Displays: Hello, world!
greet()  # Can be called multiple times

Functions with Parameters

Parameters allow passing data to the function:

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

greet("Ana")    # Hello, Ana!
greet("Bob")    # Hello, Bob!

Multiple parameters:

def introduce(name, age):
    print(f"My name is {name} and I am {age} years old")

introduce("Ana", 20)  # My name is Ana and I am 20 years old

The return Statement

return returns a value and terminates the function:

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

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

# Direct use
print(add(10, 20))  # 30

Functions without return:

Functions without return implicitly return None:

def display(message):
    print(message)
    # No return

result = display("Test")
print(result)  # None

Multiple return:

def operations(a, b):
    total = a + b
    difference = a - b
    product = a * b
    return total, difference, product  # Returns tuple

s, d, p = operations(10, 3)
print(s, d, p)  # 13 7 30

# Or as tuple
result = operations(10, 3)
print(result)  # (13, 7, 30)

Return before end:

def check_positive(n):
    if n <= 0:
        return False  # Exits immediately
    # Code that only runs for n > 0
    return True

print(check_positive(5))   # True
print(check_positive(-3))  # False

Variable Scope

Local variables:

Variables defined in a function are local - they only exist within the function:

def func():
    x = 10  # Local variable
    print(x)

func()  # 10
# print(x)  # NameError: name 'x' is not defined

Global variables:

Variables defined outside functions are global:

message = "Hello"  # Global variable

def display():
    print(message)  # Can read global variable

display()  # Hello

Modifying global variables:

To modify a global variable, use global:

counter = 0

def increment():
    global counter  # Declares using global variable
    counter += 1

increment()
print(counter)  # 1
increment()
print(counter)  # 2

Note: Avoid excessive use of global - it can make code hard to understand.

Docstrings

Document the function with a docstring:

def calculate_area(length, width):
    """
    Calculates the area of a rectangle.

    Args:
        length: The length of the rectangle
        width: The width of the rectangle

    Returns:
        The area of the rectangle (length * width)
    """
    return length * width

# View docstring
print(calculate_area.__doc__)
help(calculate_area)

Functions as Objects

In Python, functions are first-class objects:

def greet():
    return "Hello!"

# Assign to a variable
f = greet
print(f())  # Hello!

# Pass as argument
def execute(function):
    return function()

print(execute(greet))  # Hello!

Common Patterns

Validation function:

def is_even(n):
    return n % 2 == 0

print(is_even(4))  # True
print(is_even(7))  # False

Transformation function:

def celsius_to_fahrenheit(c):
    return c * 9/5 + 32

print(celsius_to_fahrenheit(0))    # 32.0
print(celsius_to_fahrenheit(100))  # 212.0

Function with list:

def sum_list(numbers):
    total = 0
    for n in numbers:
        total += n
    return total

print(sum_list([1, 2, 3, 4, 5]))  # 15

Common Mistakes

1. Forgetting parentheses when calling

def greet():
    return "Hello!"

print(greet)   # <function greet at 0x...>
print(greet()) # Hello!

2. Modifying lists in functions

def add_element(lst):
    lst.append(4)  # Modifies the original list!

numbers = [1, 2, 3]
add_element(numbers)
print(numbers)  # [1, 2, 3, 4]

3. Return in loop

def find_even(numbers):
    for n in numbers:
        if n % 2 == 0:
            return n  # Returns FIRST even
    return None

print(find_even([1, 3, 4, 6]))  # 4 (not 6!)

4. Confusion print vs return

def sum_print(a, b):
    print(a + b)  # Only displays

def sum_return(a, b):
    return a + b  # Returns value

r1 = sum_print(2, 3)   # Displays 5, r1 = None
r2 = sum_return(2, 3)  # r2 = 5

Key Points for Exam

  • def defines a function
  • return returns value and terminates function
  • Functions without return return None
  • Local variables exist only in function
  • Use global to modify global variables
  • Functions can return multiple values (as tuple)
  • Parentheses () are required when calling!

Review Questions

  1. What does a function without return return?
  2. What’s the difference between parameter and argument?
  3. What happens to local variables after function ends?
  4. How do you document a function in Python?

📚 Related Articles