for ''target'' in sequence:
''block-of-code-to-execute''
where target gets the value of the current number in sequence.
for i in range(0,10):
print(i)
gives the output
0
1
2
3
4
5
6
7
8
9
for i in range(0,10,2):
print(i)
gives the output
0
2
4
6
8
nums = [1,2,3,-1,5,6]
list_ok = True
for i in nums:
if i < 0:
list_ok = False
break
if list_ok == False:
print('The list contains a negative number')
gives the output
The list contains a negative number
nums = [1,2,3,-1,5,6]
pos_sum = 0
for i in nums:
if i < 0:
continue
pos_sum += i # compound assignment means pos_sum = pos_sum + i
print('Sum of positive numbers is ' + str(pos_sum))
gives the output
Sum of positive numbers is 17
for i in range(0,10):
print(i)
else:
print('done') # Prints numbers 0-9 and the 'done'
gives the output
0
1
2
3
4
5
6
7
8
9
done
for i in range(0,10):
if i == 5:
break
print(i)
else:
print('done') # Prints numbers 0-4
gives the output
0
1
2
3
4
sum = 0
while sum < 10:
sum += 1 # ALWAYS remember to update the loop test or it will
# run forever!!
print(sum) # Gives value 10
gives the output
10