9.2. Conditional If

  • if is a block statement

  • It's content must be indented by the same number of spaces

  • Python uses convention of 4 spaces per indent level

  • Python uses indentation instead of braces

  • Code indented on the same level belongs to block

  • PEP 8 -- Style Guide for Python Code: 4 spaces indentation

  • Python throws IndentationError exception on problem

Syntax:

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

9.2.1. Oneline Block

  • block statement

  • content should be indented

  • 4 spaces

>>> if True:
...     print('First line of the true statement')
First line of the true statement

9.2.2. Multiline Blocks

  • if is a block statement

  • It's content must be indented by the same number of spaces

  • Python uses convention of 4 spaces per indent level

  • Python uses indentation instead of braces

>>> if True:
...     print('First line of the true statement')
...     print('Second line of the true statement')
...     print('Third line of the true statement')
First line of the true statement
Second line of the true statement
Third line of the true statement

9.2.3. Nested Blocks

  • Block statement inside of a block statement

  • Content should be at the same level of indentation

  • Multiple of 4 spaces

>>> if True:
...     print('First line of the true statement')
...     print('Second line of the true statement')
...     if True:
...         print('First line of inner true statement')
First line of the true statement
Second line of the true statement
First line of inner true statement

Deeply nested blocks:

>>> if True:
...     print('Outer block, true statement, first line')
...     print('Outer block, true statement, second line')
...     print('Outer block, true statement, third line')
...
...     if True:
...         print('Inner block, true statement, first line')
...         print('Inner block, true statement, second line')
...         print('Inner block, true statement, third line')
...     else:
...         print('Inner block, else statement, fist line')
...         print('Inner block, else statement, second line')
...         print('Inner block, else statement, third line')
...
... else:
...     print('Outer block, else statement, first line')
...     print('Outer block, else statement, second line')
...     print('Outer block, else statement, third line')
Outer block, true statement, first line
Outer block, true statement, second line
Outer block, true statement, third line
Inner block, true statement, first line
Inner block, true statement, second line
Inner block, true statement, third line

9.2.4. Single Condition

  • if x < value

>>> age = 9
>>>
>>> if age < 18:
...     print('yes')
yes

9.2.5. Multiple Conditions

  • if min <= x and x < max

>>> age = 9
>>>
>>> if 0 <= age and age < 18:
...     print('yes')
yes

9.2.6. Boundary Check

  • if min <= x < max

>>> age = 9
>>>
>>> if 0 <= age < 18:
...     print('yes')
yes

9.2.7. Checking if True

  • if data is True - recommended

  • if data == True

  • if data

Is True (recommended):

>>> data = True
>>>
>>> if data is True:
...     print('yes')
yes

Equals True:

>>> data = True
>>>
>>> if data == True:
...     print('yes')
yes

Or:

>>> data = True
>>>
>>> if data:
...     print('yes')
yes

9.2.8. Checking If False

  • if data is False - recommended

  • if data == False

  • if not data

Is False (recommended):

>>> data = False
>>>
>>> if data is False:
...     print('yes')
yes

Equals False:

>>> data = False
>>>
>>> if data == False:
...     print('yes')
yes

Or:

>>> data = False
>>>
>>> if not data:
...     print('yes')
yes

9.2.9. Checking If None

  • if data is None

  • if data is not None

Is None (recommended):

>>> data = None
>>>
>>> if data is None:
...     print('yes')
yes

Is not None:

>>> data = None
>>>
>>> if data is not None:
...     print('yes')

9.2.10. Conditional Assignment

  • Define variable based on evaluation

  • if cond: x = value

>>> age = 9
>>>
>>> if age < 18:
...     status = 'junior'
>>>
>>> print(status)
junior

9.2.11. Use Case - 1

  • Even

>>> number = 4
>>>
>>> if number % 2 == 0:
...     print('even')
even

9.2.12. Recap

  • if is a block statement

  • It's content must be indented by the same number of spaces

  • Python uses convention of 4 spaces per indent level

  • Python uses indentation instead of braces

  • Code indented on the same level belongs to block

  • PEP 8 -- Style Guide for Python Code: 4 spaces indentation

  • Python throws IndentationError exception on problem

9.2.13. Further Reading

9.2.14. Assignments

# %% About
# - Name: Conditional If Junior
# - Difficulty: easy
# - Lines: 2
# - 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. If variable AGE is below 18, then set variable `result` to 'junior'
# 2. Use `if` block
# 3. Run doctests - all must succeed

# %% Polish
# 1. Jeżeli zmienna AGE jest poniżej 18, to ustaw zmienną `result` na 'junior'
# 2. Użyj bloku `if`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> 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'

>>> from pprint import pprint
>>> pprint(result)
'junior'
"""

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

# %% Imports

# %% Types
result: str

# %% Data
AGE = 7

# %% Result
result = ...

# %% About
# - Name: Conditional If Color
# - Difficulty: easy
# - Lines: 6
# - Minutes: 3

# %% 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. 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 `if` 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 `if`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> 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
"""

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

# %% Imports

# %% Types
red: int
green: int
blue: int

# %% Data
COLOR = 'red'

red = 0
green = 0
blue = 0

# %% Result

# %% About
# - Name: Conditional Elif Segmentation
# - Difficulty: easy
# - Lines: 6
# - Minutes: 3

# %% 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. If variable `NUMBER` 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 `if` blocks
# 3. Run doctests - all must succeed

# %% Polish
# 1. Jeżeli zmienna `NUMBER` 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 `if`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Doctests
"""
>>> 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}
"""

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

# %% Imports

# %% Types
result: dict[str, int]

# %% Data
NUMBER = 5

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

# %% Result