10.1. Loop 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              # i = 1
>>> print(data[i])      # data[1]
b
>>>
>>> i += 1              # i = 2
>>> print(data[i])      # data[2]
c
>>>
>>> i += 1              # i = 3
>>> 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']
>>> len(data)
3
>>> data = ['a', 'b', 'c']
>>> i = 0
>>>
>>> if i < len(data):
...     print(data[i])  # data[0]
...     i += 1          # i = 1
a
>>>
>>> if i < len(data):   # True
...     print(data[i])  # data[1]
...     i += 1          # i = 2
b
>>>
>>> if i < len(data):   # True
...     print(data[i])  # data[2]
...     i += 1          # i = 3
c
>>>
>>> if i < len(data):   # False
...     print(data[i])  # will not execute
...     i += 1          # will not execute

10.1.5. While Loop

>>> data = ['a', 'b', 'c']
>>> i = 0
>>>
>>> while i < len(data):
...     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:

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

10.1.7. Good Practices

  • 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

"""
* Assignment: Loop While Range
* Type: class assignment
* Complexity: easy
* Lines of code: 5 lines
* Time: 3 min

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 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 = ...

"""
* Assignment: Loop For Count
* Type: class assignment
* Complexity: easy
* Lines of code: 10 lines
* Time: 8 min

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

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

Tests:
    >>> import sys; sys.tracebacklimit = 0

    >>> 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 COLOR is:
# - 'red' then increment variable `red` by 1
# - 'green' then increment variable `green` by 1
# - 'blue' then increment variable `blue` by 1
...

"""
* Assignment: Loop While toFloat
* Type: class assignment
* Complexity: easy
* Lines of code: 5 lines
* Time: 5 min

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

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

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

    >>> result
    [2.0, 3.0, 3.5, 4.0, 4.5, 5.0]
"""

DATA = (2, 3, 3.5, 4, 4.5, 5)

# Values from DATA converted to float
# type: list[float]
result = ...

"""
* Assignment: Loop While toStr
* Type: class assignment
* Complexity: easy
* Lines of code: 4 lines
* Time: 5 min

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

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

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

# Joined DATA values
# type: str
result = ...

"""
* Assignment: Loop While Translate
* Type: class assignment
* Complexity: medium
* Lines of code: 5 lines
* Time: 5 min

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

    >>> 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 = ...