Prev: - Break, continue, pass | Next: range
for iterator in iterable:
block-1
else:
block-2
See an example:
# a simple example with the list [1,2,3,4,5] as iterable
asum = 0
for i in [1,2,3,4,5]:
asum += i
print(i, asum)
print('for loop is now over')
- The list [1,2,3,4,5] is used as an iterable in this example.
- The values [1,2,3,4,5] are returned (that is: assigned one-by-one) to the iterator variable 'i'.
- In each iteration the variable asum is increased by adding the current value of i in the running iteration
- The for loop is iterrated over five times (as many as the values of the iterable list returned). After the sequence of values is exhausted the for loop ends also automatically.
Lists will be thoroughly discussed in next sections. A simple list is used in this introductory example as it provides a nice visualization of a sequence of values, returned one-by-one to the itetrator
for i in ['spam','eggs','ham']: # List of strings as iterable object in the loop
print(i, end=' ')
print('\n')
m = 'spam'
for ch in m: # String as iterable object
print(ch)
# In the following examples try first to guess the print() outcomes..
#.. and then run the code to assess your understanding
alist = ['a','b','c','d','e']
ch = ''
for i in alist:
ch += i
print(ch)
v = 0
for b in [True, False]:
v +=1
if b:
print(v)
print(v)
alist = ['a','b','c']
i = 0
s=''
for ch in alist:
i +=2
s = s+i*ch
print(s)
# multiplication table
# Python convention: Constant values are written with capital letters
# 'Constant' means that the programmer will not change these values during code execution
MIN = 1
MAX = 10
for i in range(MIN, MAX+1):
for j in range(MIN, MAX+1):
print('\t', i*j, end='') # try both prints and observe the difference
#print('{:8d}'.format(i*j), end='')
print()
totalsum = evensum = 0
for i in range(1,11):
totalsum += i
if i%2: continue
evensum += i
else:
print(totalsum, evensum)
print('for loop is now over')
. Free learning material
. See full copyright and disclaimer notice