5. for loop

5.1. Syntax

5.1.1. Generic syntax

  • DATA must implement iterator interface

  • More on iterators in chapter Iterators

Listing 6. for loop syntax
for <MY VARIABLE> in <DATA> :
    <CONTENT>

5.1.2. Example

Listing 7. for loop syntax: printing each number from list
DATA = ['a', 'b', 'c']

for letter in DATA:
    print(letter)

# 'a'
# 'b'
# 'c'
Listing 8. for loop syntax: data can be inline
for letter in ['a', 'b', 'c']:
    print(letter)

# 'a'
# 'b'
# 'c'

5.2. Iterating over str

  • Iterating str will get character on each iteration

Listing 9. Iterating over str
for letter in 'setosa':
    print(letter)

# s
# e
# t
# o
# s
# a

5.3. Iterating simple collections

5.3.1. Iterating over list

Listing 10. Iterating over list
DATA = [5.1, 3.5, 1.4, 0.2, 'setosa']

for element in DATA:
    print(element)

# 5.1
# 3.5
# 1.4
# 0.2
# 'setosa'

5.3.2. Iterating over tuple

Listing 11. Iterating over tuple
DATA = (5.1, 3.5, 1.4, 0.2, 'setosa')

for element in DATA:
    print(element)

# 5.1
# 3.5
# 1.4
# 0.2
# 'setosa'

5.3.3. Iterating over set

Listing 12. Iterating over set
DATA = {5.1, 3.5, 1.4, 0.2, 'setosa'}

for element in DATA:
    print(element)

# 5.1
# 3.5
# 1.4
# 0.2
# 'setosa'

5.4. Working with Generators and Iterators

5.4.1. Loops with range

  • range(start, stop, step)

  • range(0, 3) will generate (0, 1, 2)

  • start is inclusive, default: 0

  • stop is exclusive, required

  • step default: 1

Listing 13. Loops with range
for number in range(0, 3):
    print(number)

# 0
# 1
# 2
Listing 14. Loops with range
for number in range(4, 11, 2):
    print(number)

# 4
# 6
# 8
# 10

5.4.2. enumerate

  • Pythonic way

  • Preferred over i=0 and i+=1 for every iteration

  • enumerate() will return counter and value for every iteration

Listing 15. enumerate() will return counter and value for every iteration
DATA = ['a', 'b', 'c']

for i, letter in enumerate(DATA):
    print(f'{i} -> {letter}')

# 0 -> a
# 1 -> b
# 2 -> c
Listing 16. enumerate() can start with custom number
DATA = ['a', 'b', 'c']

for i, letter in enumerate(DATA, start=5):
    print(f'{i}, {letter}')

# 5 -> a
# 6 -> b
# 7 -> c

5.5. Assignments

5.5.1. Counter

  • Complexity level: easy

  • Lines of code to write: 6 lines

  • Estimated time of completion: 5 min

  • Filename: solution/for_counter.py

English
  1. For input data (see below)

  2. Count occurrences of each number

  3. Print counter: Dict[int, int]:

    • key - number

    • value - number of occurrences

Polish
  1. Dla danych wejściowych (patrz poniżej)

  2. Policz wystąpienia każdej z cyfr

  3. Wypisz counter: Dict[int, int]:

    • klucz - liczba

    • wartość - liczba wystąpień

Input
INPUT = [1, 4, 6, 7, 4, 4, 4, 5, 1, 7, 0,
         0, 6, 5, 0, 0, 9, 7, 0, 4, 4, 8,
         2, 4, 0, 0, 1, 9, 1, 7, 8, 8, 9,
         1, 3, 5, 6, 8, 2, 8, 1, 3, 9, 5,
         4, 8, 1, 9, 6, 3]
The whys and wherefores
  • Defining dict

  • Updating dict

  • Iterating over sequences

5.5.2. Segmentation

English
  1. For input data (see below)

  2. Count occurrences of each group

  3. Define groups:

    • small - numbers in range [0-2]

    • medium - numbers in range [3-7]

    • large - numbers in range [8-9]

  4. Print counter: Dict[str, int]:

    • key - group

    • value - number of occurrences

Polish
  1. Dla danych wejściowych (patrz poniżej)

  2. Policz wystąpienia każdej z group

  3. Zdefiniuj grupy

    • small - liczby z przedziału [0-2]

    • medium - liczby z przedziału [3-7]

    • large - liczby z przedziału [8-9]

  4. Wypisz counter: Dict[str, int]:

    • klucz - grupa

    • wartość - liczba wystąpień

Input
INPUT = [1, 4, 6, 7, 4, 4, 4, 5, 1, 7, 0,
         0, 6, 5, 0, 0, 9, 7, 0, 4, 4, 8,
         2, 4, 0, 0, 1, 9, 1, 7, 8, 8, 9,
         1, 3, 5, 6, 8, 2, 8, 1, 3, 9, 5,
         4, 8, 1, 9, 6, 3]
The whys and wherefores
  • Defining dict

  • Updating dict

  • Iterating over sequences

5.5.3. Text analysis

English
  1. Given is text of the "Moon Speech" by John F. Kennedy's (see below)

  2. Sentences are separated by period (.)

  3. Clean each sentence from whitespaces at the beginning and at the end

  4. Words are separated by spaces

  5. Count how many words are there in every sentence

  6. Print Dict[str, int]:

    • key - sentence

    • value - number of words

  7. Print the total number in whole text:

    • adverbs (words ending with "ly")

    • sentences

    • words

    • letters

    • characters (including spaces inside sentences, but without periods .)

    • comas (,)

Polish
  1. Dany jest tekst przemówienia "Moon Speech" wygłoszonej przez John F. Kennedy'ego (patrz poniżej)

  2. Zdania oddzielone są kropkami (.)

  3. Każde zdanie oczyść z białych znaków na początku i końcu

  4. Słowa oddzielone są spacjami

  5. Policz ile jest słów w każdym zdaniu

  6. Wypisz Dict[str, int]:

    • klucz - zdanie

    • wartość - liczba słów

  7. Wypisz także ile jest łącznie w całym tekście:

    • przysłówków (słów zakończonych na "ly")

    • zdań

    • słów

    • liter

    • znaków (łącznie ze spacjami wewnątrz zdań, ale bez kropek .)

    • przecinków (,)

The whys and wherefores
  • String splitting

  • Calculating lengths

  • Iterating over string

  • Variable naming convention

  • Good variable names

Listing 17. "Moon Speech" by John F. Kennedy, Rice Stadium, Houston, TX, 1962-09-12 [Ken62]
We choose to go to the Moon. We choose to go to the Moon in this decade and do the other things. Not because they are easy, but because they are hard. Because that goal will serve to organize and measure the best of our energies and skills. Because that challenge is one that we are willing to accept. One we are unwilling to postpone. And one we intend to win