9.4. Conditional Elif

  • Used to check for additional condition if first is not met

  • In other languages is known as else if

  • Conditional Alternative

Syntax:

>>> 
... if <condition>:
...     <do something>
... elif <condition>:
...     <do something>
... else:
...     <do something>

9.4.1. Problem

  • With many ifs, Python will evaluate all of them

  • With elifs Python will stop, after first True evaluation

>>> age = 9
>>>
>>> if 0 <= age < 18:
...     print('junior')
junior
>>>
>>> if 18 <= age < 65:
...     print('adult')
>>>
>>> if 65 <= age:
...     print('senior')

9.4.2. Solution

  • With elif Python will stop, after first True evaluation

  • Multiple elif

  • Optional else

>>> age = 9
>>>
>>> if 0 <= age < 18:
...     print('junior')
... elif 18 <= age < 65:
...     print('adult')
... elif 65 <= age < 130:
...     print('senior')
... else:
...     print('invalid age')
junior

9.4.3. Use Case - 1

SetUp:

>>> # Simulate user input (for test automation):
>>> from unittest.mock import MagicMock
>>> input = MagicMock(side_effect=['Polish'])

Code:

>>> language = input('What is your language?: ')  # User input 'Polish'
>>>
>>> if language == 'English':
...     print('Hello')
... elif language == 'German':
...     print('Guten Tag')
... elif language == 'Polish':
...     print('Witaj')
... else:
...     print('Unknown language')
Witaj

9.4.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: Conditional Elif Color
# - Difficulty: easy
# - Lines: 6
# - Minutes: 3

# %% English
# 1. If variable COLOR is:
#    - 'red' then increment variable `red` by 1
#    - 'green' then increment variable `green` by 1
#    - 'blue' then increment variable `blue` by 1
# 2. Use `elif` blocks
# 3. Run doctests - all must succeed

# %% Polish
# 1. Jeżeli zmienna COLOR jest:
#    - 'red' to zwiększ zmienną `red` o 1
#    - 'green' to zwiększ zmienną `green` o 1
#    - 'blue' to zwiększ zmienną `blue` o 1
# 2. Użyj bloków `elif`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

>>> from pprint import pprint

>>> assert red is not Ellipsis, \
'Assign your result to variable `red`'
>>> assert green is not Ellipsis, \
'Assign your result to variable `green`'
>>> assert blue is not Ellipsis, \
'Assign your result to variable `blue`'

>>> assert type(red) is int, \
'Variable `red` has invalid type, should be int'
>>> assert type(green) is int, \
'Variable `green` has invalid type, should be int'
>>> assert type(blue) is int, \
'Variable `blue` has invalid type, should be int'

>>> pprint(red)
1
>>> pprint(green)
0
>>> pprint(blue)
0
"""

COLOR = 'red'

red = 0
green = 0
blue = 0

# If variable COLOR is:
# - 'red' then increment variable `red` by 1
# - 'green' then increment variable `green` by 1
# - 'blue' then increment variable `blue` by 1
# Use `elif` blocks
...


# %% 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: Conditional Elif Segmentation
# - Difficulty: easy
# - Lines: 6
# - Minutes: 3

# %% English
# 1. If variable DIGIT is in range:
#    - from 0 to 3 (exclusive) - then increment variable `result['small']` by 1
#    - from 3 to 7 (exclusive) - then increment variable `result['medium']` by 1
#    - from 7 to 10 (exclusive) - then increment variable `result['large']` by 1
# 2. Use `elif` blocks
# 3. Run doctests - all must succeed

# %% Polish
# 1. Jeżeli zmienna DIGIT jest w zakresie:
#    - od 0 do 3 (rozłącznie) - wtedy zwiększ zmienną `result['small']` o 1
#    - od 3 do 7 (rozłącznie) - wtedy zwiększ zmienną `result['medium']` o 1
#    - od 7 do 10 (rozłącznie) - wtedy zwiększ zmienną `result['large']` o 1
# 2. Użyj bloków `elif`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

>>> from pprint import pprint

>>> assert result is not Ellipsis, \
'Assign your result to variable `result`'
>>> assert type(result) is dict, \
'Variable `red` has invalid type, should be int'

>>> assert all(type(x) is str for x in result.keys()), \
'All dict keys should be str'
>>> assert all(type(x) is int for x in result.values()), \
'All dict keys should be int'

>>> result = {'small': 0, 'medium': 1, 'large': 0}
"""

DIGIT = 5

result = {
    'small': 0,
    'medium': 0,
    'large': 0,
}

# If variable DIGIT is in range:
# - from 0 to 3 (exclusive) - then increment variable `result['small']` by 1
# - from 3 to 7 (exclusive) - then increment variable `result['medium']` by 1
# - from 7 to 10 (exclusive) - then increment variable `result['large']` by 1
# type: dict[str, int]
...