For Loops

for loops use the range() function and iterate over whatever items are in the range. for loops can also iterate over items in a list.

for statement: for i in range(n):

for loops contain the following:

  • The for keyword
  • A variable name
  • The in keyword
  • A call to the range() method with up to 3 integers passed to it
  • A colon
  • Starting on a newline, an indented for clause

Examples #

print('My name is')
for i in range(5):
    print('Jimmy Five Times (' + srt(i) + ')')

Equivalent while loop:

print('My name is')
i = 0
while i < 5:
    print('Jimmy Five Times (' + str(i) + ')')
    i = i + 1

Calculate the sum of all numbers between 1 and 100 using a for loop:

total = 0
for num in range(101):
    total = total + num
print(total)

Iterate over list items #

>>> supplies = ['pens', 'staplers', 'flamethrowers', 'binders']
>>> for item in supplies:
...     print(item)
...
pens
staplers
flamethrowers
binders
>>> for i in range(len(supplies)):
...     print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
...
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flamethrowers
Index 3 in supplies is: binders
>>>

Note: how you can iterate over the range(len(someList)) to get the indexes of a list.

See also #