3.2. Syntax Assert

  • Raises AssertionError if argument is False

  • Can have optional message

  • Running Python with the -O optimization flag disables assert statements

  • PEP 679 - Allow parentheses in assert statements https://peps.python.org/pep-0679/

>>> admins = ['mwatney', 'mlewis', 'rmartinez']
>>>
>>> assert 'avogel' in admins, 'You must be an admin to edit this page'
Traceback (most recent call last):
AssertionError: You must be an admin to edit this page

3.2.1. Assert Keyword

Note the output of the following statements:

>>> data = [1, 2, 3]
>>>
>>> 1 in data
True
>>> 4 in data
False

In both examples from above, the output is visible. We can intercept it to the variable, but we need to define it and store those values.

In the next example assert keywords allows to proceed with execution, if only the assertion is True.

>>> data = [1, 2, 3]
>>>
>>> assert 1 in data
>>>
>>> assert 4 in data
Traceback (most recent call last):
AssertionError

If the assertion is True (value 1 in a member of data) nothing will happen. However if there is an error (value 4 is not a member of data), then the exception (AssertionError) is raised.

Assertions can have additional information, which can help with debugging:

>>> data = [1, 2, 3]
>>>
>>> assert 4 in data, '4 must be in data'
Traceback (most recent call last):
AssertionError: 4 must be in data

3.2.2. Sequence Assertion

>>> data = [1, 2, 3]
>>>
>>> assert type(data) is list
>>> assert all(type(x) is int for x in data)

3.2.3. Use Case - 1

You can use assertions to check Python version.

>>> import sys
>>>
>>> assert sys.version_info >= (3, 13)
>>> assert sys.version_info >= (3, 13), 'Python 3.13+ required'

3.2.4. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Exception Assert Version
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Check value passed to a `result` function:
#    - Check if `version` is greater or equal to `REQUIRED_VERSION`
#    - If not, raise exception with message 'Python 3.13+ required'
# 2. Non-functional requirements:
#    - Write solution inside `result` function
#    - Mind the indentation level
#    - Use `assert` kyword
# 3. Run doctests - all must succeed

# %% Polish
# 1. Sprawdź poprawność wartości przekazanej do funckji `result`:
#    - Sprawdź czy `version` jest większe lub równe `REQUIRED_VERSION`
#    - Jeżeli nie, podnieś wyjątek z komunikatem 'Python 3.13+ required'
# 2. Wymagania niefunkcjonalne:
#    - Rozwiązanie zapisz wewnątrz funkcji `result`
#    - Zwróć uwagę na poziom wcięć
#    - Użyj słowa kluczowego `assert`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `assert`
# - `>=`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> result( (3,11) )
Traceback (most recent call last):
AssertionError: Python 3.13+ required

>>> result( (3,12) )
Traceback (most recent call last):
AssertionError: Python 3.13+ required

>>> result( (3,12,4) )
Traceback (most recent call last):
AssertionError: Python 3.13+ required

>>> result( (3,13) )
>>> result( (3,13,0) )
>>> result( (3,13,0,) )

>>> result( (3,14) )
>>> result( (3,14,0) )
>>> result( (3,14,0,'alpha') )
>>> result( (3,14,0,'beta') )
>>> result( (3,14,0,'rc') )
"""

REQUIRED_VERSION = (3, 13)


def result(version):
    ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Exception Assert Types
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3

# %% English
# 1. Check value passed to a `add_numbers` function:
#    - assert that type of `a` or `b` is int or float
#    - if not, raise assertion error with message:
#      'Parameter `a` must be int or float'
# 2. Non-functional requirements:
#    - Write solution inside `add_numbers` function
#    - Mind the indentation level
#    - Use `assert` kyword
# 3. Run doctests - all must succeed

# %% Polish
# 1. Sprawdź poprawność wartości przekazanej do funckji `add_numbers`:
#    - zapewnij, że typ `a` oraz `b` jest int lub float
#    - jeżeli nie, podnieś błąd asercji z komunikatem:
#      'Parameter `a` must be int or float'
# 2. Wymagania niefunkcjonalne:
#    - Rozwiązanie zapisz wewnątrz funkcji `add_numbers`
#    - Zwróć uwagę na poziom wcięć
#    - Użyj słowa kluczowego `assert`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `assert`
# - `isinstance()`
# - `type()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> add_numbers(1, 0)
1
>>> add_numbers(0, 1)
1
>>> add_numbers(1.0, 0)
1.0
>>> add_numbers(0, 1.0)
1.0
>>> add_numbers('1', 0)
Traceback (most recent call last):
AssertionError: Parameter `a` must be int or float
>>> add_numbers(0, '1')
Traceback (most recent call last):
AssertionError: Parameter `b` must be int or float
>>> add_numbers([1], 0)
Traceback (most recent call last):
AssertionError: Parameter `a` must be int or float
>>> add_numbers(0, [1])
Traceback (most recent call last):
AssertionError: Parameter `b` must be int or float
>>> add_numbers(True, 0)
Traceback (most recent call last):
AssertionError: Parameter `a` must be int or float
>>> add_numbers(0, False)
Traceback (most recent call last):
AssertionError: Parameter `b` must be int or float
"""

def add_numbers(a, b):
    return a + b


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Exception Assert Len
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Check value passed to a `check` function:
#    - assert that argument `data` has length of 3
#    - if not, raise assertion error
# 2. Non-functional requirements:
#    - Write solution inside `check` function
#    - Mind the indentation level
#    - Use `assert` kyword
# 3. Run doctests - all must succeed

# %% Polish
# 1. Sprawdź poprawność wartości przekazanej do funckji `check`:
#    - zapewnij, że argument `data` ma długość 3
#    - jeżeli nie, podnieś błąd asercji
# 2. Wymagania niefunkcjonalne:
#    - Rozwiązanie zapisz wewnątrz funkcji `check`
#    - Zwróć uwagę na poziom wcięć
#    - Użyj słowa kluczowego `assert`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `assert`
# - `len()`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> check([1, 2, 3, 4, 5])
Traceback (most recent call last):
AssertionError
>>> check([1, 2, 3, 4])
Traceback (most recent call last):
AssertionError
>>> check([1, 2, 3])
>>> check([1, 2])
Traceback (most recent call last):
AssertionError
>>> check([1])
Traceback (most recent call last):
AssertionError
>>> check([])
Traceback (most recent call last):
AssertionError
"""

def check(data):
    ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Exception Assert Set
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3

# %% English
# 1. Check value passed to a `check` function:
#    - assert that `data: set` contains numbers: 1, 2 and 3
#    - if not, raise assertion error
# 2. Non-functional requirements:
#    - Write solution inside `check` function
#    - Mind the indentation level
#    - Use `assert` kyword
# 3. Run doctests - all must succeed

# %% Polish
# 1. Sprawdź poprawność wartości przekazanej do funckji `check`:
#    - zapewnij, że `data: set` ma liczby: 1, 2 i 3
#    - jeżeli nie, podnieś błąd asercji
# 2. Wymagania niefunkcjonalne:
#    - Rozwiązanie zapisz wewnątrz funkcji `check`
#    - Zwróć uwagę na poziom wcięć
#    - Użyj słowa kluczowego `assert`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `assert`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> check({1, 2, 3})
>>> check({1, 3, 2})
>>> check({2, 1, 3})
>>> check({2, 3, 1})
>>> check({3, 1, 2})
>>> check({3, 2, 1})
>>> check({1, 2})
Traceback (most recent call last):
AssertionError
>>> check({1, 3})
Traceback (most recent call last):
AssertionError
>>> check({2, 1})
Traceback (most recent call last):
AssertionError
>>> check({2, 3})
Traceback (most recent call last):
AssertionError
>>> check({3, 1})
Traceback (most recent call last):
AssertionError
>>> check({3, 2})
Traceback (most recent call last):
AssertionError
>>> check({1})
Traceback (most recent call last):
AssertionError
>>> check({2})
Traceback (most recent call last):
AssertionError
>>> check({3})
Traceback (most recent call last):
AssertionError
"""

def check(data):
    ...