10.1. While About

  • Iterate over sequences (iterables)

  • Repeat if until result is False

10.1.1. Syntax

  • Continue execution when argument is True

  • Stops if argument is False

Generic syntax:

while <condition>:
    <do something>

Example:

>>> 
... while True:
...     pass

10.1.2. Getitem with Const

>>> data = ['a', 'b', 'c']
>>>
>>>
>>> print(data[0])
a
>>>
>>> print(data[1])
b
>>>
>>> print(data[2])
c
>>>
>>> print(data[3])
Traceback (most recent call last):
IndexError: list index out of range

10.1.3. Getitem with Variable

>>> data = ['a', 'b', 'c']
>>> i = 0               # i = 0
>>>
>>>
>>> print(data[i])      # data[0]
a
>>> i += 1
>>>
>>>
>>> print(data[i])      # data[1]
b
>>> i += 1
>>>
>>>
>>> print(data[i])      # data[2]
c
>>> i += 1
>>>
>>> print(data[i])      # data[3]
Traceback (most recent call last):
IndexError: list index out of range

10.1.4. Getitem with Boundary Checking

>>> data = ['a', 'b', 'c']
>>> until = len(data)  # 3
>>> i = 0
>>>
>>> if i < until:       # True
...     print(data[i])  # data[0]
...     i += 1          # i = 1
a
>>>
>>> if i < until:       # True
...     print(data[i])  # data[1]
...     i += 1          # i = 2
b
>>>
>>> if i < until:       # True
...     print(data[i])  # data[2]
...     i += 1          # i = 3
c
>>>
>>> if i < until:       # False
...     print(data[i])  # will not execute
...     i += 1          # will not execute

10.1.5. While Loop

>>> data = ['a', 'b', 'c']
>>> until = len(data)  # 3
>>> i = 0
>>>
>>> while i < until:
...     print(data[i])
...     i += 1
a
b
c

10.1.6. Sequence Iteration

Better idea for this is to use for loop. for loop supports Iterators. len() must write all numbers to memory, to calculate its length:

>>> data = ['a', 'b', 'c']
>>>
>>> i = 0
>>> while i < 3:
...     print(i, data[i])
...     i += 1
0 a
1 b
2 c
>>> data = ['a', 'b', 'c']
>>>
>>> i = 0
>>> until = 3
>>> while i < until:
...     print(i, data[i])
...     i += 1
0 a
1 b
2 c
>>> data = ['a', 'b', 'c']
>>>
>>> i = 0
>>> until = len(data)
>>> while i < until:
...     print(i, data[i])
...     i += 1
0 a
1 b
2 c

10.1.7. Convention

  • The longer the loop scope, the longer the variable name should be

  • Avoid one letters if scope is longer than one line

  • Use i for loop counter (it is traditional name in almost all languages)

10.1.8. 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: While About Range
# - Difficulty: easy
# - Lines: 5
# - Minutes: 3

# %% English
# 1. Generate `result: list[int]` with numbers from 0 to 5 (exclusive)
# 2. Do not use `range()`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Wygeneruj `result: list[int]` z liczbami od 0 do 5 (rozłącznie)
# 2. Nie używaj `range()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

>>> assert type(result) is list
>>> assert all(type(x) is int for x in result)

>>> result
[0, 1, 2, 3, 4]
"""


# List with numbers from 0 to 5 (exclusive)
# type: list[int]
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: While About Count
# - Difficulty: easy
# - Lines: 10
# - Minutes: 8

# %% English
# 1. Count occurrences of each color in `DATA`
# 2. Do not use `list.count()`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zlicz wystąpienia każdego z kolorów w `DATA`
# 2. Nie używaj `list.count()`
# 3. Uruchom doctesty - wszystkie muszą się powieść

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

>>> 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 list'
>>> assert type(green) is int, \
'Variable `green` has invalid type, should be list'
>>> assert type(blue) is int, \
'Variable `blue` has invalid type, should be list'

>>> red
3
>>> green
2
>>> blue
2
"""

DATA = ['red', 'green', 'blue', 'red', 'green', 'red', 'blue']

red = 0
green = 0
blue = 0

# If variable DATA is:
# - 'red' then increment variable `red` by 1
# - 'green' then increment variable `green` by 1
# - 'blue' then increment variable `blue` by 1
...


# %% 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: While About To Float
# - Difficulty: easy
# - Lines: 5
# - Minutes: 5

# %% English
# 1. Create `result: list[float]`
# 2. Use `while` to iterate over `DATA`
# 3. Convert current elements of `DATA` to `float`
# 4. Converted value append to `result`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Stwórz `result: list[float]`
# 2. Użyj `while` do iterowania po `DATA`
# 3. Przekonwertuj obecny element `DATA` do `float`
# 4. Przekonwertowaną wartość dodaj na koniec `result`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `Stop` or `Ctrl+C` kills infinite loop

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

>>> type(result)
<class 'list'>

>>> assert all(type(x) is float for x in result)

>>> result
[1.0, 2.0, 3.0]
"""

DATA = (1, 2, 3)

# Values from DATA converted to float
# type: list[float]
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: While About To Str
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5

# %% English
# 1. Create `result: str`
# 2. Use `while` to iterate over `DATA`
# 3. Add current element of `DATA` to `result`
# 4. Do not use `str.join()`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Stwórz `result: str`
# 2. Użyj `while` do iterowania po `DATA`
# 3. Dodaj obecny element z `DATA` do `result`
# 4. Nie używaj `str.join()`
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `Stop` or `Ctrl+C` kills infinite loop

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

>>> type(result)
<class 'str'>
>>> result
'hello'
"""

DATA = ['h', 'e', 'l', 'l', 'o']

# Joined DATA values
# 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: While About Remove PL Chars
# - Difficulty: medium
# - Lines: 5
# - Minutes: 5

# %% English
# 1. Use `while` to iterate over `DATA`
# 2. If letter is in `PL` then use conversion value as letter
# 3. Add letter to `result`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Użyj `while` do iteracji po `DATA`
# 2. Jeżeli litera jest w `PL` to użyj skonwertowanej wartości jako litera
# 3. Dodaj literę do `result`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - `Stop` or `Ctrl+C` kills infinite loop

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

>>> type(result)
<class 'str'>
>>> result
'zazolc gesla jazn'
"""

PL = {
    'ą': 'a',
    'ć': 'c',
    'ę': 'e',
    'ł': 'l',
    'ń': 'n',
    'ó': 'o',
    'ś': 's',
    'ż': 'z',
    'ź': 'z',
}

DATA = 'zażółć gęślą jaźń'

# DATA with substituted PL diacritic chars to ASCII letters
# type: str
result = ...