Programming

Python functions: def, parameters and return

How to write and call a function.

All lessons · Python lessons: learn from scratch

Defining a function

A function lets you avoid repeating code. You need the def keyword, a name, parameters in brackets and a colon.

def greet(name):
    print("Hello,", name)

greet("Aysel")
greet("Murad")

return and results

print writes to the screen; return hands the value back so you can store it in a variable.

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

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

Default value: def power(x, n=2). If you forget return the function gives None — a common surprise.

Author: Nibras Code