For loop

  • for is a keyword
  • iterates
  • iterables
    • list, tuple, set, dictionary, string
  • body of the for loop, executed for each iteration
VA_birds = ["mockingbird", "robin", "woodpecker", "cardinal"]
for birdtype in VA_birds:
    print(f'{birdtype} can be found in Virginia')

Body of the for loop

sum = 0
grades = [75, 81, 65, 83, 88]
for grade in grades:
    sum += grade
average = sum/len(grades)
print(f'Your average is {average}')

range()

  • generates a sequence of integers
  • range object that is immutable
  • three values
    • starting integer, default 0
    • ending integer, integers generated up to but not include ending
    • integer step value, default 1
      range(4)
      range(10, 20)
      range(100, 10000, 50)
      range(10, 0)

for loop with range()

year_started = int(input("enter the year you started at JMU: "))
print("My four years at JMU")
for year in range(year_started, year_started + 4):
    print(year)

checkpoint 1

  • write a python for loop to print all the numbers from 1 to 105 that are evenly divisible by 3 and not even
for num in range (1, 106):
    if num % 3 == 0 and num % 2:
        print(num)

for loops and dictionaries

calories = {'apple': 72,
            'bagel': 290,
            'chicken breast' : 150,
            'ice cream' : 160
            }
for food_item in calories:
    print(f'{food_item} has {calories[food_item]} calories')
# same results
for food_item, number in calories.items():
    print(f'{food_item} has {number} calories')

enumerate

  • iterate through a sequence
    • index and corresponding element
  • combination range() and len()
    • then index into the sequence for value
  • enumerate() function
    • pass an iterable (string, list, tuple, set, dictionary)
    • returns an enumerate object
      • adds a counter index to each corresponding element value

Checkpoint 2: try these

names = ['Bob', 'Sally', 'John', 'Nathan']
enumerate_info = enumerate(names)
print(names)
print(list(enumerate_info))
  • enumerate() yields a new tuple each itertion of the loop
names = ['Bob', 'Sally', 'John', 'Nathan']
for who in enumerate(names):
    print(who)
  • enumrate()
    • returns a tuple
    • can be unpacked into two variables
names = ['Bob', 'Sally', 'John', 'Nathan']
for order, who in enumerate(names):
    print(order, who)

Recap of for loops

Code Meaning
for value in my_list: for each value in a list
for index in range(len(my_list)): for each index in a list
for index, value in enumerate(my_list): for each index and value
for key in my_dict: for each key in a dict
for key, value in my_dict.items(): For each key and value

Other Concepts in this chapter

  • incremental programming
  • function stubs
    • pass
  • keyword function arguments
  • default parameter values