</>CodexBash
Python
PythonBeginner10 min

Functions

Defining functions with def, parameters and return values, default and keyword arguments, where variables live, and why small named functions make code easier.

How a function call returnsstep 1/6
main
in = main
The program starts in main. The stack holds one frame: main's own variables.

A function is a named block of code you can run whenever you need it. You have been using them already: print, len, int. Now you write your own.

Defining and calling#

def greet(name):
    print(f"Hello, {name}")

greet("Asha")     # Hello, Asha
greet("Ravi")     # Hello, Ravi

def starts the definition, name is a parameter (a variable that receives the value passed in), and the indented block is the body. Defining a function does nothing on its own; calling it runs the body.

Returning a value#

Most useful functions hand a result back with return:

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

room = area(4, 3)
print(room)              # 12
print(area(2, 5) + 1)    # 11

return ends the function immediately. A function with no return gives back None, which is a common surprise:

def double(x):
    x * 2            # calculated, then thrown away

print(double(4))     # None

Returning early#

return inside an if is a clean way to handle special cases first:

def sign(n):
    if n > 0:
        return "positive"
    if n < 0:
        return "negative"
    return "zero"

Several results#

Return several values separated by commas, and unpack them at the call:

def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([4, 9, 1, 7])
print(low, high)     # 1 9

Default and keyword arguments#

A parameter can have a default, used when the caller leaves it out:

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

power(5)        # 25
power(5, 3)     # 125

Callers can name arguments, which makes calls with several values easier to read:

power(exponent=3, base=2)     # 8

Where variables live#

A variable created inside a function exists only inside it:

def make_total():
    total = 10
    return total

make_total()
print(total)     # NameError: total only existed inside the function

This is a feature: functions do not trip over each other's names. Pass values in through parameters and get results out through return, rather than reaching for variables outside.

Lists are shared, numbers are not#

Changing a number inside a function never affects the caller. Changing a list does, because the function receives the same list, not a copy:

def add_one(numbers):
    numbers.append(1)

values = [5]
add_one(values)
print(values)    # [5, 1]

Sometimes that is what you want. When it is not, work on a copy: numbers = numbers.copy().

Docstrings#

A string on the first line of a function describes it, and tools show it as help:

def is_vowel(c):
    """Whether c is a vowel, in either case."""
    return c.lower() in "aeiou"

Why bother#

A function with a good name lets the rest of the program read like a description:

count = sum(1 for c in text if is_vowel(c))

Each function can be tested and fixed on its own, and written once instead of copied. If you find yourself copying a few lines and changing one detail, that detail wants to be a parameter.

Key points#

  • def name(parameters): defines a function; calling it runs the body.
  • return gives back a value and ends the function; no return means None.
  • Defaults make parameters optional; naming arguments makes calls clearer.
  • Variables made inside a function stay inside it.
  • A list passed in can be changed by the function.

Next: storing many values together, with lists.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedHow many digitsEasy
  2. Not startedIs it a palindromeEasy
Create a free account to track your progress