Defining functions

Topic 1 of 5 in Functions6 min readBeginnerFree course

Overview

You’ve been calling functions since your first line: print(), len(), input(). Now you’ll write your own. A function is a named block of code that you define once and run whenever you need it. Functions are how programmers stay sane: they turn a long script into small, named, testable steps.

Why functions?

  • Reuse — write the logic once, use it many times.
  • Naming — is_valid_email(text) explains itself; twenty lines of string checks don’t.
  • Fixing in one place — a bug in a function is fixed everywhere it’s used.
  • Testing — small functions are easy to check (Testing with pytest).

Defining and calling

Anatomy of a function. def area(width, height=1): — def, the name and the parameters in brackets, ending with a colon. “”“Return the area of a rectangle.”“” is a docstring saying what it does. The indented body, result = width * height, does the work; return result sends a value back. print(area(3, 4)) calls it with arguments and shows 12. height=1 is a default: area(5) works and returns 5. Without return, a function returns None.

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

greet("Asha")      # Hello, Asha!
greet("Ben")       # Hello, Ben!
  • def starts the definition, followed by the function’s name, parameters in brackets, and a colon.
  • The indented body is the code that runs.
  • Defining a function doesn’t run it. The body runs each time the function is called: greet("Asha").
  • A function must be defined (its def must have run) before it’s called.

Parameters and arguments

The names in the definition are parameters; the values you pass in a call are arguments. Each call fills the parameters with that call’s arguments:

Python
def rectangle_area(width, height):
    return width * height

rectangle_area(3, 4)       # width=3, height=4 → 12
rectangle_area(10, 2)      # width=10, height=2 → 20

Pass the wrong number and Python tells you:

Text
TypeError: rectangle_area() missing 1 required positional argument: 'height'

Parameters and arguments covers defaults, keyword arguments and more.

return: sending a result back

return ends the function and hands a value back to wherever it was called. The call expression becomes that value:

Python
def rectangle_area(width, height):
    return width * height

area = rectangle_area(3, 4)       # area is 12
print(rectangle_area(3, 4) * 2)   # 24 — use it in an expression

A function without a return (or with a bare return) returns None:

Python
result = greet("Asha")    # prints Hello, Asha!
print(result)             # None

Return, don’t print

Beginners often write functions that print their result:

Python
def rectangle_area(width, height):
    print(width * height)        # shows it... and then it's gone

That function can’t be used in a calculation, saved to a file, or tested. Return the value and let the caller decide whether to print it. Reserve printing for functions whose whole job is output, like greet.

Functions returning booleans

Functions that answer a yes/no question read nicely in if statements. Name them like questions:

Python
def is_even(n):
    return n % 2 == 0

if is_even(len(players)):
    print("Teams are equal")

Note return n % 2 == 0 — not if n % 2 == 0: return True else: return False. The comparison already is True or False.

Functions calling functions

Functions can use other functions — that’s how you build up bigger programs from small pieces:

Python
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

def describe_temperature(c):
    f = celsius_to_fahrenheit(c)
    return f"{c}°C is {f}°F"

print(describe_temperature(20))    # 20°C is 68.0°F

Structuring a program

A common layout for a script: definitions at the top, then the code that uses them — often in a main() function:

Python
def get_total(prices):
    return sum(prices)

def main():
    prices = [3.5, 12.0, 7.25]
    print("Total:", get_total(prices))

main()

Modules and imports explains the if __name__ == "__main__": line you’ll often see around that final call.

Naming and size

  • Use snake_case verbs: calculate_total, send_email, is_valid, get_user.
  • Keep functions short — if it doesn’t fit on your screen, it’s probably doing several jobs.
  • One job each. If you describe a function with “and” (“loads the file and calculates totals and prints a report”), split it.

Remember: def defines, brackets call, return gives back. Prefer returning values over printing them.

Exercise

A small toolbox of functions

Write four functions and call each one to show it works. (1) greet(name) prints Hello, <name>!. (2) rectangle_area(width, height) returns the area. (3) is_even(n) returns True or False. (4) celsius_to_fahrenheit(c) returns c × 9/5 + 32. Then use them together: print the area of a 3 × 4 rectangle, whether that area is even, and convert 0, 37 and 100 °C in a loop, printing e.g. 37°C = 98.6°F.

Python
# 1. greet(name)

# 2. rectangle_area(width, height)

# 3. is_even(n)

# 4. celsius_to_fahrenheit(c)

# Use them

Summary

  • def name(parameters): defines a function; the indented body runs only when the function is called.
  • Call a function with brackets: name(arguments); arguments fill the parameters in order.
  • return value sends a result back to the caller and ends the function; without it, the function returns None.
  • Return values rather than printing them, so the caller can decide what to do with the result.
  • Good functions do one job, have a verb-like name, and are short enough to read at a glance.