Python Level 6: Functions

Goal of this Level

Today you will learn to:

By the end, you will be able to write programs that are organized, shorter, and reusable.

Step 1: What is a Function?

A function is a block of code that performs a specific task.

Benefits:

Real-life example:

A coffee machine is like a function.

You press a button → coffee is made.

In programming:

You call a function → it executes code.

Step 2: Creating a Function

A function is created with def.


def hello():
    print("Hello!")

Explanation:

Step 3: Calling a Function

To execute a function, you must call it.


def hello():
    print("Hello!")

hello()

Output:


Hello!

Step 4: Functions with Parameters

Parameters are information that a function receives.


def greeting(name):
    print("Hello", name)

greeting("Anna")
greeting("Max")

Output:


Hello Anna
Hello Max

Explanation:

Step 5: Return Values

Sometimes a function should return a result.

For that, use return.


def greeting(name):
    return "Hello " + name

print(greeting("Anna"))

Output:


Hello Anna

Explanation:

Step 6: Function with Calculation

Functions are very useful for math or calculations.


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

print(add(3, 4))

Output:


7

Explanation:

Practice Example


def greeting(name):
    return "Hello " + name

print(greeting("Anna"))

What happens here:

More Examples

Example 1:


def square(number):
    return number * number

print(square(5))

Output:


25

Example 2:


def welcome(name, age):
    print("Hello", name)
    print("You are", age, "years old")

welcome("Max", 20)

Task

Write a function that adds two numbers and returns the result.

Steps:

Example structure:


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

print(add_numbers(5, 3))

Output:


8