When writing Python code, you will often find yourself repeating the same steps. Instead of writing them again and again, you can put those steps into a function. A function is a reusable block of code that has a name and can be run whenever you call it.
Function syntax
A basic function looks like this:
def function_name():
# code to run
print("Hello, world!")
defis the keyword that tells Python you are defining a function.function_nameis the name of your function.- The brackets
()follow the name. These are used for inputs (called parameters). - A colon
:starts the function block. - Everything indented underneath is what the function does.
To use the function, you simply call it:
function_name()
Naming conventions
- Use lowercase letters.
- Use underscores to separate words, e.g.
calculate_total. - Pick names that explain what the function does.
Parameters and return values
Functions can take parameters to customise their behaviour:
def greet(name):
print(f"Hello, {name}!")
They can also return values:
def add(a, b):
return a + b
Docstrings: explaining your functions
A docstring is a short description written inside triple quotes at the start of a function. It tells others (and your future self) what the function is meant to do.
def greet(name):
"""Print a friendly greeting using the given name."""
print(f"Hello, {name}!")
You can see the docstring by using the built-in help() function:
help(greet)
This is very useful when you come back to your code later or when you are working in a team.
Things to try yourself
- Write a function called
say_hellothat prints your name, and add a docstring. - Create a function called
squarethat returns the square of a number. Usehelp(square)to read its docstring. - Write a function called
is_eventhat returnsTrueif a number is even. Document it with a docstring that explains the input and the output.
👉 Functions are like building blocks. With docstrings, they are not only reusable but also self-explaining, which makes your code easier to read, share, and maintain.




