A Python function is a named block of code you can run whenever you need it. Instead of writing the same five lines in three places, you write them once, give them a name, and call that name. Functions are the point where beginner programs become organised programs. This guide explains Python functions for beginners, step by step.
Why functions exist
- Reuse: write the code once, use it many times.
- Readability:
calculate_tax(price)says what is happening; twelve lines of arithmetic do not. - Fixing: a bug in a function is fixed in one place, everywhere at once.
- Thinking: big problems become a set of small, named steps.
You have been using functions from day one: print(), input(), len(). Now you write your own.
Defining and calling a function
def greet():
print("Hello!")
print("Welcome to Python.")
greet() # runs the two lines
greet() # and again
defstarts the definition, followed by the name, brackets and a colon.- The indented lines are the function's body.
- Defining a function does not run it. Calling it โ
greet()โ does.
Parameters: giving a function information
Most functions need something to work on. Name it in the brackets:
def greet(name):
print(f"Hello, {name}!")
greet("Ana") # Hello, Ana!
greet("Leo") # Hello, Leo!
Here name is a parameter โ a placeholder in the definition. "Ana" is an argument โ the actual value passed in when you call it. Functions can take several:
def describe(name, age):
print(f"{name} is {age} years old.")
describe("Sam", 34)
return versus print: the big one
This confuses almost every beginner, so it is worth slowing down.
print()shows a value on the screen. The rest of your program cannot use it.returnhands a value back to the code that called the function, so it can be stored and used.
def add_print(a, b):
print(a + b)
def add_return(a, b):
return a + b
x = add_print(2, 3) # shows 5, but x is None
y = add_return(2, 3) # shows nothing, but y is 5
print(y * 10) # 50
A rule that serves beginners well: functions that calculate something should return it, and printing should happen in the code that calls them. That makes the function useful in more places โ you can print the result, save it, or use it in another calculation.
When Python reaches return, the function stops immediately. A function with no return gives back None.
Default values
Give a parameter a default, and callers can leave it out:
def price_with_tax(price, rate=0.2):
return price * (1 + rate)
print(price_with_tax(100)) # 120.0
print(price_with_tax(100, 0.05)) # 105.0
Parameters with defaults go after those without.
Scope: where variables live
Variables created inside a function exist only inside it:
def make_total():
total = 10
make_total()
print(total) # NameError: name 'total' is not defined
This is a feature, not a limitation: each function has its own private workspace, so functions cannot accidentally overwrite each other's variables. To get a value out, return it:
def make_total():
total = 10
return total
result = make_total()
print(result) # 10
A worked example
Here is a small program that uses functions to keep each job separate:
def average(numbers):
return sum(numbers) / len(numbers)
def grade(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 60:
return "C"
return "Needs work"
scores = [92, 78, 64]
avg = average(scores)
print(f"Average: {avg:.1f} โ grade {grade(avg)}")
# Average: 78.0 โ grade B
Each function does one thing and has a name that says what. The main code at the bottom reads almost like a sentence. Notice how the functions work with a list; the same style works just as well with dictionaries.
Common mistakes
- Forgetting the brackets:
greetrefers to the function;greet()runs it. - Printing instead of returning, then wondering why the result is
None. - Calling a function before defining it โ Python reads top to bottom, so definitions come first.
- Functions that do too much. If you cannot name it in a few words, split it.
- Missing colon or indentation after
defโ see Python errors beginners make.
Practise
- Write
square(n)that returnsn * n. - Write
is_even(n)that returnsTrueorFalse. - Write
initials(first, last)that returns something like"A.L.". - Rebuild a calculator with one function per operation โ project nine in our Python projects for complete beginners.
Functions have a full part of Python for Beginners to themselves: defining and calling, arguments and parameters, return values and scope, lambda functions, and error handling with try/except, finishing with test questions. Graded exercises with reference solutions are in the free Practice Toolkit on the book's page.
Frequently asked questions
What is the difference between a parameter and an argument?
A parameter is the name in the function's definition. An argument is the value you pass in when calling it.
Can a function return more than one value?
Yes: return low, high returns both as a tuple, which you can unpack with a, b = my_function().
When should I write a function?
When you have written the same code twice, or when a block of code does one clear job you can name.