Lesson 9 – Functions

A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you write it once inside a function and call it whenever needed. Functions help make your programs organised, cleaner, and easier to maintain.

What Does a Function Look Like?

A function has two parts: 1. Definition – where you create the function 2. Call – where you tell Python to run it

Example 1: A Simple Function

def greet():
    print("Hello, welcome to Python!")

greet()
        

Output:

Hello, welcome to Python!
        

Example 2: Function With Parameters

Parameters let your function receive information.

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

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

Output:

8
        

Example 3: Function Returning Text

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

print(welcome("Khalid"))
        

Output:

Hello Khalid
        

Why Use Functions?


Quiz: Test Your Understanding

1. What is a function?

A type of variable
A loop that repeats code
A reusable block of code
A Python library
Correct answer: A reusable block of code

2. What keyword is used to create a function?

func
def
create
make
Correct answer: def

3. What does a return statement do?

Stops the program
Sends a value back from a function
Prints text on the screen
Makes a loop repeat
Correct answer: Sends a value back from a function

4. What will this print?

def test(x):
    return x * 2

print(test(4))
            
2
4
6
8
Correct answer: 8

5. What is the output of this code?

def hello():
    print("Hi")

hello()
            
hello
Hi
error
nothing
Correct answer: Hi
Back to Top