Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 8

Loops part 1: for and range

FreeLesson 10 of 78

A loop repeats code for every item in a collection. This is where programs start saving you real time.

LOOP OVER A LIST AND A STRINGPYTHON 3.12
amounts = [1198, 796, 1499, 1999]

for amount in amounts:          # amount takes each value in turn
    print("order of", amount)

for letter in "Pune":           # strings are collections too
    print(letter, end=" ")
print()

Output

order of 1198
order of 796
order of 1499
order of 1999
P u n e
RANGE: LOOPS THAT COUNTPYTHON 3.12
print(list(range(5)))           # 0 up to 4 (5 is not included)
print(list(range(1, 6)))        # 1 up to 5
print(list(range(0, 20, 5)))    # steps of 5
print(list(range(5, 0, -1)))    # counting down

for day in range(1, 4):
    print(f"processing day {day}")

Output

[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]
processing day 1
processing day 2
processing day 3
THE THREE LOOP PATTERNS YOU WILL USE FOREVERPYTHON 3.12
amounts = [1198, 796, 1499, 1999, 1348]

total, count, biggest = 0, 0, amounts[0]
for a in amounts:
    total += a                  # accumulate
    count += 1                  # count
    if a > biggest:             # track the maximum
        biggest = a
print(total, count, biggest, round(total / count, 1))

for i, a in enumerate(amounts, start=1):   # position + value
    if a > 1400:
        print(f"order #{i} is big: {a}")

Output

6840 5 1999 1368.0
order #3 is big: 1499
order #4 is big: 1999

Try it yourself before moving on

  1. Print the 7 times table from 7 x 1 to 7 x 10.
  2. Add up all the odd numbers from 1 to 99 with range and a step.
  3. Print each city in a list with its position, starting at 1.

Watch the free lesson

The same topic in the Free Lessons library, free with a sign-in.