Functions in Python — an introduction (Thonny)
In this lesson we will get to know the idea of functions in Python. A function is a special part of a program that does one particular thing — for example, printing a message, adding numbers or checking a condition.
You can imagine a function as a small machine: when you start it, it does exactly what it was made for.
Functions help make a program shorter, more readable and easier to understand, especially when the program gets bigger. Instead of writing the same code several times, you write it once — in a function.
Working in Thonny is ideal for beginners: you write code, save the file and run it by pressing the Run button. When you use functions, you can do the same task several times without writing the code again.
Why use functions?
- Better organisation — the program is divided into logical parts.
- Fewer mistakes — the same code is not repeated several times.
- Easier learning — every function has a clear role.
- Easier changes — you change the code in one place.
Writing a function and calling it
It is important to understand the difference between:
- writing (defining) a function
- calling (using) a function
When you write a function, it does not run straight away. It runs only when you call it.
A simple example of a function
Let us start with the simplest possible function — a function that only prints a message.
# function_example.py
def greet():
print("Hello! Welcome to Python functions.")
# calling the function
greet()
What happens here?
def— the keyword we use to define a functiongreet— the name of the function()— brackets that show that this is a functionprint()— the code that runs when the function is called
If you delete the line greet(), the message will not be printed —
because the function exists, but it has not been called.
One more example
A function can contain several lines of code.
def show_message():
print("Python is fun!")
print("We are learning functions step by step.")
show_message()
All the lines that are indented under def
make up the body of the function.
Mini task
Write a function that prints your name and your favourite school subject. Then call that function.
def about_me():
print("My name is Ana.")
print("My favourite subject is computer science.")
about_me()
In the next lesson we will learn how functions can take data (parameters) and return a result — just like mathematical formulas.
Common beginner mistakes with functions
When you are just learning functions, it is normal to make mistakes. Below are the most common mistakes and how to avoid them.
1. Wrong indentation
In Python indentation is required. All the lines that belong to a function must be indented.
Wrong:
def greet():
print("Hello!")
This will cause an error because print is not indented.
Correct:
def greet():
print("Hello!")
✔ Tip: in Thonny use Tab or 4 spaces.
2. A forgotten function call
Beginners often write a function but forget to call it. In that case nothing happens when you run the program.
Wrong (the function never runs):
def greet():
print("Hello!")
Correct:
def greet():
print("Hello!")
greet()
3. Do not forget the brackets
A function is always called with brackets.
Wrong:
greet
Correct:
greet()
4. The name of the function must be the same
Python tells capital and small letters apart.
If you called the function greet, you cannot call it as Greet.
def greet():
print("Hello!")
greet() # correct
Greet() # error
If you get an error — do not worry. Mistakes are part of learning and mean that you are on the right track.
How Python runs functions – step by step
To make functions completely clear, it is important to understand when the code runs, and when Python only "remembers" what the function should do.
1. What happens when Python reads a function?
Look at the following example:
def greet():
print("Hello!")
print("End of the program")
When you run this program, the output will be:
End of the program
The message "Hello!" is not printed.
Why?
- Python only remembered what the function looks like
- The body of the function does not run until you call it
Defining a function is not the same as running it.
2. When does a function REALLY run?
A function runs only when you write its name with brackets:
def greet():
print("Hello!")
greet()
print("End of the program")
Now the order of execution is:
- Python reads the definition of the function
- It comes to the call
greet() - The program "enters" the function
- The body of the function runs
- The program goes back and continues
3. A visual flow of execution (a block diagram)
You can imagine the execution like this:
START OF THE PROGRAM
|
v
Function definition (nothing runs)
|
v
Function call
|
v
Entering the function
|
v
Running the lines in the function
|
v
Back to the main program
|
v
THE PROGRAM CONTINUES
This way of thinking is very useful for more complex programs.
4. A common beginner mistake: "Why is nothing happening?"
If you write a function but do not call it:
def message():
print("This will not be printed")
The program runs without an error — but without any output. That is normal behaviour in Python.
Always check whether:
- the function exists
- the function is called
5. An important warning about the file name
When you make a file with Python code, do not use generic names that can clash with Python modules.
❌ Bad examples of file names:
string.pymath.pyrandom.py
If you do that, Python may try to load your file instead of the built-in module — which leads to confusing errors.
✔ Good examples:
my_functions.pyfunctions_intro.pyfunctions_practice.py
Extra practice tasks — functions in Python (Thonny)
Here are suggested tasks that extend the material from the page and are suitable for practising in the Thonny environment. For each task there is a short description, a starting function skeleton and a short note or a test example.
- Greet the user (a parameter)
Make a function that takes a name and prints a personalised greeting.
def greet_name(name): # print for example "Hello, Ana!" pass # an example call greet_name("Ana")Note: try different names and empty strings.
- Add two numbers (return a value)
The function takes two numbers and returns their sum. Then print the result outside the function.
def add(a, b): # return the sum pass # example: result = add(5, 7) print("Result:", result) - Checking whether a number is even
Write a function
is_even(n)that returnsTrueif the number is even, otherwiseFalse.def is_even(n): pass print(is_even(4)) # True print(is_even(7)) # False - Factorial (iterative)
The function
fact(n)calculates n!. Start with an iterative approach (a loop).def fact(n): # assume n >= 0 pass print(fact(5)) # 120Bonus: also try a recursive version if you are ready for a challenge.
- The biggest of three numbers
The function returns the biggest of three given numbers (do not use
max— solve it with logic).def maximum3(a, b, c): pass print(maximum3(3, 9, 5)) # 9 - Count the vowels
The function takes a text and returns how many vowels (a, e, i, o, u) it has. Ignore capital/small letters.
def count_vowels(text): # return the number of vowels pass print(count_vowels("Welcome to Python")) - The average of a list of numbers
The function returns the average value of the elements of a list. Make sure the list is not empty.
def average(values): # return the average value pass print(average([2, 4, 6, 8])) # 5.0 - A palindrome (check)
A function that checks whether a word (or a phrase without spaces) is a palindrome. Ignore capital/small letters and spaces.
def is_palindrome(s): # for example "Ana" -> True pass print(is_palindrome("Ana")) print(is_palindrome("no palindrome")) - Text statistics (returns several values)
The function takes a text and returns a tuple: (
number_of_words,number_of_characters). Show the result in the main program.def text_statistics(text): # return (number_of_words, number_of_characters) pass r = text_statistics("This is a short text.") print(r) - A small calculator (with a default parameter)
Write a function
calculator(a, b, op='+')that supports addition, subtraction, multiplication and division (op can be '+', '-', '*', '/'). The function returns the result orNoneif the operation is unknown.def calculator(a, b, op='+'): # op: '+', '-', '*', '/' pass print(calculator(10, 3, '*')) print(calculator(10, 0, '/')) # take care of division by zero
Bonus challenge
FizzBuzz — write a function that, for the numbers from 1 to n, prints: "Fizz" if the number is divisible by 3, "Buzz" if it is divisible by 5, "FizzBuzz" if it is divisible by both, otherwise the number. This is a great task for combining loops and functions.
def fizzbuzz(n):
pass
fizzbuzz(15)
How to practise: open Thonny, make a new file, copy the function skeletons and fill in the function bodies step by step. Test every task with several values.
Hidden mini quiz — functions in Python
Click to check whether you understand what functions are, how they are defined, how they are called and how the code inside a function behaves.
Open the quiz
Mini quiz: functions
1. What will happen if a function is not called?
2. What does the following program print?
def message():
print("Hello")
message()
3. How many times will the message be printed?
def test():
print("Python")
test()
test()
Tasks for independent work — functions (7th and 8th grade)
The tasks go from easier to harder. The last task is close to competition level. Try to solve each task on your own before you move on to the next one.
- Printing a message
Write a function that prints the message: "I am learning functions in Python". Call the function twice.
- A function with one parameter
Write a function that takes a student's name and prints the message: "The student <name> has successfully run the function."
- Adding numbers
Write a function that takes two whole numbers and returns their sum. Print the result in the main program.
- A function that checks a condition
Write a function that takes one number and returns the message "Positive", "Negative" or "Zero".
Hint: use
if,elifandelseinside the function and return a text value. - Competition level — repeated function calls
Write a function that takes one whole number
nand prints all the numbers from 1 ton, but so that the printing is done by an extra function that prints one number.Hint: use one function for the logic (the loop), and another only for printing. Think about why this is a good programming style.
