// python · beginner
Python Functions Made Simple: def, Parameters and return
Learn how to write your own Python functions, pass in parameters, return results, use default values, and understand the difference between print and return.
As your programs grow, you’ll notice yourself writing the same few lines again and again. Functions let you write those lines once, give them a name, and use them wherever you need them. They make code shorter, easier to read and much easier to fix.
You’ve already used functions
print(), input(), len() and int() are all functions that come with Python. You call a function by writing its name followed by brackets, with any inputs inside:
length = len("CodeRunner")
print(length) # 10
Now let’s write our own.
Defining a function
def greet():
print("Hello!")
print("Welcome to CodeRunner.")
greet()
greet()
defstarts the definition, followed by the function’s name, brackets and a colon.- The indented lines underneath are the function’s body.
- Defining a function doesn’t run it. The code only runs when you call it with
greet().
Parameters: giving a function inputs
A parameter is a variable that receives a value when the function is called:
def greet(name):
print(f"Hello, {name}!")
greet("Ava") # Hello, Ava!
greet("Leo") # Hello, Leo!
The value you pass in ("Ava") is called an argument. A function can take several parameters, separated by commas:
def describe(name, language):
print(f"{name} is learning {language}.")
describe("Ava", "Python")
return: getting a result back
Many functions calculate something and hand the answer back with return:
def area(width, height):
return width * height
room = area(4, 5)
print(room) # 20
print(area(2, 3)) # 6
As soon as Python reaches return, it leaves the function and the call is replaced by the returned value. That’s why you can store it in a variable or use it inside another expression.
print vs return: the big confusion
These two functions look similar but behave very differently:
def add_print(a, b):
print(a + b)
def add_return(a, b):
return a + b
x = add_print(2, 3) # shows 5 on screen
y = add_return(2, 3) # shows nothing
print(x) # None
print(y) # 5
printshows a value to the person running the program, then it’s gone.returngives a value back to your code so you can keep using it.
A function without a return gives back the special value None. As a rule of thumb, functions that calculate things should return; let the rest of your program decide whether to print.
Default parameter values
You can give a parameter a default, used when no argument is passed:
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25 (uses the default exponent of 2)
print(power(2, 10)) # 1024
Parameters with defaults must come after the ones without.
Scope: variables inside stay inside
A variable created inside a function only exists inside that function:
def make_total():
total = 100
make_total()
print(total) # NameError: name 'total' is not defined
This is called local scope, and it’s a good thing: functions can’t accidentally mess up each other’s variables. If you need a value outside the function, return it.
Mini project: a temperature converter
def c_to_f(celsius):
return celsius * 9 / 5 + 32
def f_to_c(fahrenheit):
return (fahrenheit - 32) * 5 / 9
choice = input("Convert (1) °C to °F or (2) °F to °C? ")
value = float(input("Temperature: "))
if choice == "1":
print(f"{value}°C is {c_to_f(value):.1f}°F")
else:
print(f"{value}°F is {f_to_c(value):.1f}°C")
Each function does one small job and is easy to test on its own: c_to_f(100) should give 212.0, and f_to_c(32) should give 0.0.
Tips for writing good functions
- One job per function. If you need the word “and” to describe it, consider splitting it.
- Name it with a verb:
calculate_total,get_username,is_valid_email. - Keep them short. If a function no longer fits on your screen, it’s probably doing too much.
Key points
- Define with
def name(parameters):and call withname(arguments). returnhands a value back;printjust shows it.- Default values make parameters optional.
- Variables created inside a function are local to it.
Test yourself on everything so far in PyQuest, our free Python quiz game. Then learn how to work with text in Working with Strings in Python.