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

# %% 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 If Junior
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% 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ść

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

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

AGE = 7

# If variable AGE is below 18, then set variable `result` to 'junior'
# Use `if` block
# 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 If Contains
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. If variable `DATA` contains 'x', then set variable `result` to True
# 2. Use `if` block
# 3. Run doctests - all must succeed

# %% Polish
# 1. Jeżei zmienna `DATA` zawiera 'x', to ustaw zmienną `result` na True
# 2. Użyj bloku `if`
# 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'

>>> from pprint import pprint
>>> pprint(result)
True
"""

DATA = ['a', 'b', 'c', 'x']

# If variable `DATA` contains 'x', then set variable `result` to True
# Use `if` block
# 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 If 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 `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ść

# %% 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 `if` block
...


# %% 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 `if` 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 `if`
# 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
# Use `if` blocks
# type: dict[str, int]
...


# %% 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 If Login
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. If:
#    - variable `USERNAME` is equal to 'mwatney'
#    - variable `PASSWORD` is equal to 'Ares3'
#    - then set variable `result` to True
# 2. Use `if` block
# 3. Run doctests - all must succeed

# %% Polish
# 1. Jeżeli:
#    - zmienna `USERNAME` jest równa 'mwatney'
#    - zmienna `PASSWORD` jest równa 'Ares3'
#    - to ustaw zmienną `result` na True
# 2. Użyj bloku `if`
# 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'

>>> from pprint import pprint
>>> pprint(result)
True
"""

USERNAME = 'mwatney'
PASSWORD = 'Ares3'

# If:
# - variable `USERNAME` is equal to 'mwatney'
# - variable `PASSWORD` is equal to 'Ares3'
# - then set variable `result` to True
# Use `if` block
# 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 If Auth
# - Difficulty: easy
# - Lines: 2
# - Minutes: 5

# %% English
# 1. Write authentication system
# 2. User will provide two strings: `USERNAME` and `PASSWORD`
# 3. Check if `USERNAME` is in the `DATABASE` and if the `PASSWORD` matches
# 4. If both matches, then define variable `result` with value `True`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Napisz system uwierzytelniania
# 2. Użytkownik poda dwa ciągi znaków: `USERNAME` i `PASSWORD`
# 3. Sprawdź czy `USERNAME` jest w `DATABASE` i czy `PASSWORD` pasuje
# 4. Jeżeli oba pasują, to zdefiniuj zmienną `result` z wartością `True`
# 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'

>>> from pprint import pprint
>>> pprint(result)
True
"""

DATABASE = {
    'mwatney': 'Ares3',
    'mlewis': 'Nasa69',
    'rmartinez': 'Mav3',
    'avogel': 'Chem1',
    'bjohanssen': 'Root0',
    'cbeck': 'DoctorNo1'
}

USERNAME = 'mwatney'
PASSWORD = 'Ares3'


# Write authentication system
# User will provide two strings: `USERNAME` and `PASSWORD`
# Check if `USERNAME` is in the `DATABASE` and if the `PASSWORD` matches
# If both matches, then define variable `result` with value `True`
# type: bool
result = ...