🐍 Python

Functions

Lesson 4 of 5 ~7 min

Functions let you organize code into reusable blocks. Define a function once, call it anywhere. Python functions are defined with the def keyword.

Defining and calling functions

Editor
Python
Output

Try it

Change the name and title arguments. Try adding a new parameter to the function.

Parameters and return values

# Basic function
def add(a, b):
    return a + b

result = add(3, 5)    # 8

# Default arguments
def power(base, exponent=2):
    return base ** exponent

print(power(3))       # 9
print(power(3, 3))    # 27

*args and **kwargs

Python gives you flexible ways to accept any number of arguments:

# *args — any number of positional arguments
def total(*args):
    return sum(args)

print(total(1, 2, 3, 4))    # 10

# **kwargs — any number of keyword arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25)

Scope

Variables created inside a function are local — they only exist within that function. Variables outside functions are global:

x = 10          # Global

def my_func():
    x = 5       # Local — different from global x
    print(x)    # 5

my_func()
print(x)        # 10 — global x is unchanged

Quiz

What keyword defines a function in Python?
Challenge

Write a function called average that takes a list of numbers and returns the average. Test it with average([10, 20, 30, 40, 50]).