Programming

Functions

Defining functions, parameters, local variables, return and docstrings.

All lessons · Python lessons: learn from scratch

Defining a function

A function is a named piece of code: write it once, call it many times. It is defined with def, parameters go in parentheses, and the result comes back with return. Without return a function gives back None.

def area(width, height):
    return width * height

print(area(4, 5))        # 20
room = area(3.5, 2)
print(room)              # 7.0

A string placed as the first line of a function is a docstring and shows up in help(area). A good function does one job and its name says which.

def is_adult(age):
    """Return True if age is 18 or more."""
    return age >= 18

Parameters

A parameter can have a default value, so the caller may leave it out. Arguments can be passed by position or by name.

def greet(name, greeting="Hello", mark="!"):
    return f"{greeting}, {name}{mark}"

print(greet("Leyla"))
print(greet("Leyla", mark="?"))
print(greet(greeting="Salam", name="Kamran"))

For an unknown number of arguments there are *args (positional) and **kwargs (named). Beware: do not use an empty list [] as a default; it is shared between calls. Use None and create a new list inside the function.

def total(*numbers):
    return sum(numbers)

def add_tag(tag, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(tag)
    return bucket

print(total(1, 2, 3, 4))   # 10
print(add_tag("a"), add_tag("b"))   # ['a'] ['b']

Variable scope

A variable created inside a function is local and invisible outside. A global variable can be read inside, but changing it requires the global keyword. In practice it is better to avoid globals and pass what you need as parameters.

rate = 0.18

def with_tax(price):
    tax = price * rate      # reads the global
    return price + tax

print(with_tax(100))
# print(tax)  -> NameError: tax exists only inside the function

Author: Nibras Code