1.7 Loops

1.7.1For

Useage Example 3

for i in range(10):
print(i)
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

Useage Example 4

names = ['Robert', 'Andrew', 'Clement', 'Linda', 'Zhi Han']

for haha in names:
print(haha + ' is very, very naughty.')
# Robert is very, very naughty.
# Andrew is very, very naughty.
# Clement is very, very naughty.
# Linda is very, very naughty.
# Zhi Han is very, very naughty.

Useage Example 5

names = ['Robert', 'Andrew', 'Clement', 'Linda', 'Zhi Han']

for i, haha in enumerate(names):
print(f'{i}:\t{haha} is very, very naughty.')
# 0:    Robert is very, very naughty.
# 1:    Andrew is very, very naughty.
# 2:    Clement is very, very naughty.
# 3:    Linda is very, very naughty.
# 4:    Zhi Han is very, very naughty.
names = ['Robert', 'Andrew', 'Clement', 'Linda', 'Zhi Han']

for i, haha in enumerate(names,100):
print(f'{i}:\t{haha} is very, very naughty.')
# 100:  Robert is very, very naughty.
# 101:  Andrew is very, very naughty.
# 102:  Clement is very, very naughty.
# 103:  Linda is very, very naughty.
# 104:  Zhi Han is very, very naughty.

1.7.2While

Useage Example 1

i = 0            # initialise the variable

while i <= 10:
i += 1       #change the value of i
print(i)
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11

1.7.3Break & Continue

Useage Example 1

i = 0            # initialise the variable

while i <= 10:
i += 1       #change the value of i
print(i)
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11

1.7.4 List Comprehension

Useage Example 1

x = [i**2 for i in range(10)]
print(x)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Useage Example 2

x = [[i,i**2] for i in range(10)]
print(x)
# [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Useage Example 3

x = ['even' if i%2 ==0 else 'odd' for i in range(10)]
print(x)
# ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

Useage Example 4

x = [i for i in range(10) if i%2==0]
print(x)
# [0, 2, 4, 6, 8]