We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Pure Function Review

Pure functions have a lot of benefits. Whenever possible, good developers try to use pure functions instead of impure functions. Remember, pure functions:

  • Return the same result if given the same arguments. They are deterministic.
  • Do not change the external state of the program. For example, they do not change any variables outside of their scope.
  • Do not perform any I/O operations (like reading from disk, accessing the internet, or writing to the console).

These properties make pure functions easier to test, debug, and think about.

Refer to the following examples to answer the questions.

Example 1

def multiply_by2(nums: list[int]) -> list[int]:
    products: list[int] = []
    for num in nums:
        products.append(num * 2)
    return products

Example 2

balance: int = 1000
cars: list[str] = []


def buy_car(new_car: str) -> None:
    global balance
    cars.append(new_car)
    balance -= 69

Example 3

import random


def roll_die(num_sides: int) -> int:
    return random.randint(1, num_sides)