Skip to content
Learnearn.uk » Home » Functions & Procedures

Functions & Procedures

Functions

Functions

In Python, functions are a way to group a set of statements together to perform a specific task. They allow you to organize your code into reusable blocks, making it easier to read, understand, and maintain. All functions must return a value using the return statement, otherwise it isn’t function – it’s a procedure.

# Function definition
def greet():
    return "Hello, world!"

# Calling the function
print(greet())  # Output: Hello, world!

Here the greet function returns the string “Hello, world!” to the program and the print function prints it out to the screen.

Input parameters

Input Parameters

Functions can also take input values (arguments or parameters) and optionally return a result. Here’s an example of a function that takes arguments and returns a value:

Here’s an example of defining and calling a simple function in Python:

# Function definition with arguments and return value
def add_numbers(x, y):
    return x + y

# Calling the function and using the returned value
result = add_numbers(5, 3)
print(result)  # Output: 8

In this example, the function add_numbers takes two arguments x and y and returns their sum. The returned value is stored in the result variable and printed.

Optional parameters & default values

Python functions can have multiple parameters, and you can define default values for some or all of the parameters. Here’s an example:

# Function definition with multiple parameters and default values
def multiply_numbers(x, y=1):
    return x * y

# Calling the function
result = multiply_numbers(4, 6)
print(result)  # Output: 24

result = multiply_numbers(5)
print(result)  # Output: 5 (default value of y is used)

 

Practice

Resources

Practice

You can practice writing your own functions using these Python functions challenges.

 

Exam Questions

June 16 Paper 22 Questions 2,3