11.5. Conditional Expression — Python
Ternary Operator -
a if CONDITION else bConditional Expression -
True if CONDITION else FalseShorthand Expressions -
result = CONDITION
11.5.1. Recap
>>> age = 7 >>> >>> if age < 18: ... status = 'junior' ... else: ... status = 'senior'
11.5.2. Ternary Operator
a if CONDITION else b
>>> age = 7 >>> status = 'junior' if age < 18 else 'senior'
11.5.3. Conditional Expression
True if CONDITION else False
>>> age = 7 >>> is_junior = True if age < 18 else False
11.5.4. Shorthand Expressions
result = CONDITION
>>> age = 7 >>> is_junior = age < 18
11.5.5. Use Case - 1
SetUp:
>>> username = 'alice' >>> password = 'secret'
Using normal if:
>>> if username == 'alice' and password == 'secret': ... print('Access Granted') ... Access Granted
Using expression 1:
>>> valid_username = (username == 'alice') >>> valid_password = (password == 'secret') >>> >>> if valid_username and valid_password: ... print('Access Granted') ... Access Granted
Using expression 2:
>>> valid_username = (username == 'alice') >>> valid_password = (password == 'secret') >>> valid_credentials = valid_username and valid_password >>> >>> if valid_credentials: ... print('Access Granted') ... Access Granted
11.5.6. Use Case - 2
Is numeric
SetUp:
>>> # Simulate user response '10' when prompted by input() >>> 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
11.5.7. Use Case - 3
Even/odd
>>> number = 3 >>> is_even = (number % 2 == 0 ) >>> >>> print(is_even) False
11.5.8. Use Case - 4
Astronaut/Cosmonaut
>>> country = 'Russia' >>> job = 'astronaut' if country == 'USA' else 'cosmonaut' >>> >>> print(job) cosmonaut
11.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
11.5.10. Assignments
# %% About # - Name: Conditional Expression Junior/Senior # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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 # %% 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ść # %% Expected # >>> result # 'senior' # %% Hints # - `<` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from pprint import pprint >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is str, \ 'Variable `result` has an invalid type; expected: `str`.' >>> assert result in {'junior', 'senior'}, \ 'Variable `result` should be either junior or senior' >>> pprint(result) 'senior' """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types result: str # %% Data AGE = 30 # %% Result result = ...
# %% About # - Name: Conditional Expression IPv4/IPv6 # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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 # %% 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ść # %% Expected # >>> result # 'IPv4' # %% 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` # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is str, \ 'Variable `result` has an invalid type; expected: `str`.' >>> assert result in ('IPv4', 'IPv6'), \ 'Variable `result` must be either `IPv4` or `IPv6`' """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types result: str # %% Data IP_ADDRESS = '127.0.0.1' # %% Result result = ...
# %% About # - Name: Conditional Expression IsDigit # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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 # %% English # 1. Check if variable `NUMBER` is a digit (numeric value between 0 and 9) # 2. Define variable `result` with the result # 3. Use shorthand expression (`result = CONDITION`) # 4. Run doctests - all must succeed # %% Polish # 1. Sprawdź czy zmienna `NUMBER` jest cyfrą (wartość liczbową między 0 a 9) # 2. Zdefiniuj zmienną `result` z wynikiem # 3. Użyj wyrażenia skróconego (`result = CONDITION`) # 4. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # True # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is bool, \ 'Variable `result` has an invalid type; expected: `bool`.' >>> result True """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types result: bool # %% Data NUMBER = 7 # %% Result result = ...