Python-a07 Loops and Iterations

This article shows the examples of Loops and Iterations in python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
## loop
nums = [1,2,3,4,5]
for num in nums:
print(num, end="; ") # 1; 2; 3; 4; 5

## break
nums = [1,2,3,4,5]
for num in nums:
if num == 3:
print('Found !', end="; ")
break
print(num, end="; ") # 1; 2; Found !

## continue
nums = [1,2,3,4,5]
for num in nums:
if num == 3:
print('Found !', end="; ")
continue
print(num, end="; ") # 1; 2; Found !; 4; 5;

## loop within loop
nums = [1,2,3]
for num in nums:
for letter in 'abc':
print(num, letter, end="; ") # 1 a; 1 b; 1 c; 2 a; 2 b; 2 c; 3 a; 3 b; 3 c;

## range
for num in range(1, 11):
print(num, end="; ") # 1; 2; 3; 4; 5; 6; 7; 8; 9; 10;

## while
x = 0
while x < 10:
print(x, end="; ")
x+=1 # 0; 1; 2; 3; 4; 5; 6; 7; 8; 9;