roxxhub

Python for loop

A ‘for’ loop is command which is used to iterate over a sequence(ex. list, tuple, dictionary, set, even a string) multiple times. Lets take a look at the syntaxes of python for loop

Looping through a list

names = ['ben', 'sam', 'tobey']    # the code
for x in names:
    print(x, 'is a member')
print('so the loop has ended ?')

thus giving us the output

ben is a member                         
sam is a member
toby is a member
so the loop has ended ?

here the ‘for’ loop goes through each element of the list (element refers to each object , or name inside the list, like ‘tobey’) and maps it as the variable x (this could be any string, like ‘y’, ‘z’, ‘members’ etc), then performs the code block after the ‘:’. (also note that the word ‘in’ after the variable is a must). so first it maps x = ‘ben’, and then performs the following command. then it maps x = ‘sam’, and then with ‘tobey’ and finally end the loop

Looping through a string

x = 'spider'                      #code
for ab in x:
    print(ab)
s
p
i
d
e
r

Iterating through multiple sequences at a time

x = (1, 2, 3)
y = ('tom', 'tim', 'dick')
for a, b in x, y:
    print('rank', a, 'is', b)
rank 1 is tom
rank 2 is tim
rank 3 is dick

NOTE: all the sequences should have the same length

How to stop a ‘for’ loop using the break command

x = [1, 2 ,3, 4, 5, 6, 7, 8, 9, 10]
for i in x:
    print(i*4)
    if i == 6:
       break    
4
8
12
16
20
24