9.5. Conditional Expression

  • Ternary Operator - a if CONDITION else b

  • Conditional Expression - True if CONDITION else False

  • Shorthand Expressions - result = CONDITION

9.5.1. Recap

>>> age = 7
>>>
>>> if age < 18:
...     status = 'junior'
... else:
...     status = 'senior'

9.5.2. Ternary Operator

  • a if CONDITION else b

>>> age = 7
>>> status = 'junior' if age < 18 else 'senior'

9.5.3. Conditional Expression

  • True if CONDITION else False

>>> age = 7
>>> is_junior = True if age < 18 else False

9.5.4. Shorthand Expressions

  • result = CONDITION

>>> age = 7
>>> is_junior = age < 18

9.5.5. Use Case - 1

  • Is adult

Simulate user input (for test automation):

>>> from unittest.mock import Mock
>>> input = Mock(side_effect=['10'])

Usage:

>>> age = input('What is your age?: ')   # input: '10'
>>> adult = 'Yes' if int(age) >= 18 else 'No'
>>>
>>> print(adult)
No

9.5.6. Use Case - 2

  • Is numeric

Simulate user input (for test automation):

>>> from unittest.mock import Mock
>>> input = Mock(side_effect=['10'])

Usage:

>>> age = input('What is your age?: ')   # input: '10'
>>> age = float(age) if age.isnumeric() else None
>>>
>>> print(age)
10.0

9.5.7. Use Case - 3

  • Even/odd

>>> number = 3
>>> is_even = (number % 2 == 0 )
>>>
>>> print(is_even)
False

9.5.8. Use Case - 4

  • Astronaut/Cosmonaut

>>> country = 'Russia'
>>> job = 'astronaut' if country == 'USA' else 'cosmonaut'
>>>
>>> print(job)
cosmonaut

9.5.9. Use Case - 5

  • IPv4/IPv6

>>> ip = '127.0.0.1'
>>> protocol = 'IPv4' if '.' in ip else 'IPv6'
>>>
>>> print(protocol)
IPv4
>>> ip = 'fe80::aede:48ff:fe01:1133'
>>> protocol = 'IPv4' if '.' in ip else 'IPv6'
>>>
>>> print(protocol)
IPv6

9.5.10. 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 Expression Junior/Senior
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Define variable `result: str` with value:
#    - 'junior' - if `AGE` is below 18
#    - 'senior' - if `AGE` is 18 or above
# 2. Use ternary operator (`a if CONDITION else b`)
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj zmienną `result: str` z wartością:
#    - 'junior' - jeżeli `AGE` jest poniżej 18 lat
#    - 'senior' - jeżeli `AGE` jest 18 lat lub więcej
# 2. Użyj ternary operator (`a if CONDITION else b`)
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `<`

# %% 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 str, \
'Variable `result` has invalid type, should be str'

>>> assert result in {'junior', 'senior'}, \
'Variable `result` should be either junior or senior'

>>> pprint(result)
'senior'
"""

AGE = 30


# Define variable `result: str` with value:
# - 'junior' - if `AGE` is below 18
# - 'senior' - if `AGE` is 18 or above
# Use ternary operator (`a if CONDITION else b`)
# type: str
result = ...


# %% 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 Expression IPv4/IPv6
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. To `result: str` assign whether `IP_ADDRESS` is IPv4 or IPv6 protocol:
#    - `IPv4` if dot `.` is in the IP address
#    - `IPv6` if dot `.` is not in the IP address
# 2. Use ternary operator (`a if CONDITION else b`)
# 3. Run doctests - all must succeed

# %% Polish
# 1. Użytkownik podał adres IP
# 1. Do `result: str` przypisz czy `IP_ADDRESS` jest protokołu IPv4 czy IPv6:
#    - `IPv4` jeżeli jest kropka `.` w adresie IP
#    - `IPv6` jeżeli kropki nie ma
# 2. Użyj ternary operator (`a if CONDITION else b`)
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `in`
# - In IPv6 address there is no dot `.`
# - IPv4 example: `127.0.0.1`
# - IPv6 example: `2001:0db8:85a3:0000:0000:8a2e:0370:7334`

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

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

>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'

>>> assert result in ('IPv4', 'IPv6'), \
'Variable `result` must be either `IPv4` or `IPv6`'
"""

IP_ADDRESS = '127.0.0.1'

# To `result: str` assign whether `IP_ADDRESS` is IPv4 or IPv6 protocol:
# - `IPv4` if dot `.` is in the IP address
# - `IPv6` if dot `.` is not in the IP address
# Use ternary operator (`a if CONDITION else b`)
# type: str
result = ...


# %% 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 Expression IsDigit
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Define `result: bool` with result of checking if `NUMBER` is digit
# 2. Use shorthand expression (`result = CONDITION`)
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: bool` z wynikiem sprawdzania czy `NUMBER` jest cyfrą
# 2. Użyj shorthand expression (`result = CONDITION`)
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

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

>>> assert type(result) is bool, \
'Variable `result` has invalid type, should be bool'

>>> result
True
"""

NUMBER = 7

# Define `result: bool` with result of checking if `NUMBER` is digit
# Use shorthand expression (`result = CONDITION`)
# type: bool
result = ...


# %% 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 Expression Modulo
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3

# %% English
# 1. Read a number from user
# 2. User will input `int` and will not try to input invalid data
# 3. Define `result: bool` with parity check of input number
# 4. Number is even, when divided modulo (`%`) by 2 reminder equal to 0
# 5. Do not use `if` statement
# 6. Run doctests - all must succeed

# %% Polish
# 1. Wczytaj liczbę od użytkownika
# 2. Użytkownika poda `int` i nie będzie próbował wprowadzać niepoprawnych danych
# 3. Zdefiniuj `result: bool` z wynikiem sprawdzania parzystości liczby wprowadzonej
# 4. Liczba jest parzysta, gdy dzielona modulo (`%`) przez 2 ma resztę równą 0
# 5. Nie używaj instrukcji `if`
# 6. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `int()`
# - `%`
# - `==`
# - `%` has different meaning for `int` and `str`
# - `%` on `str` is overloaded as a string formatting
# - `%` on `int` is overloaded as a modulo division

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

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

>>> assert type(result) is bool, \
'Variable `result` has invalid type, should be bool'

>>> result
True
"""

# Simulate user input (for test automation)
from unittest.mock import Mock
input = Mock(side_effect=['4'])


number = input('What is your number?: ')

# Whether input number is even or odd (modulo divide)
# type: bool
result = ...