2.1 Loops
2.1 Loops
ipynb - Colab
keyboard_arrow_down Loops
Video Outline:
1. Introduction to Loops
2. for Loop
3. while Loop
break
continue
pass
5. Nested Loops
range(5)
range(0, 5)
## for loop
for i in range(5):
print(i)
0
1
2
3
4
for i in range(1,6):
print(i)
1
2
3
4
5
for i in range(1,10,2):
print(i)
1
3
5
7
9
for i in range(10,1,-1):
print(i)
10
9
8
7
6
5
4
3
2
for i in range(10,1,-2):
print(i)
10
8
https://colab.research.google.com/drive/1Ac9yuG9nqrKwMtLgQS8I-EOGmdTUUbLA#printMode=true 1/4
7/18/24, 9:32 AM Loops.ipynb - Colab
6
4
2
## strings
str="Krish Naik"
for i in str:
print(i)
K
r
i
s
h
N
a
i
k
## while loop
count=0
while count<5:
print(count)
count=count+1
0
1
2
3
4
## break
## The break statement exits the loop permaturely
## break sstatement
for i in range(10):
if i==5:
break
print(i)
0
1
2
3
4
## continue
## The continue statement skips the current iteration and continues with the next.
for i in range(10):
if i%2==0:
continue
print(i)
1
3
5
7
9
https://colab.research.google.com/drive/1Ac9yuG9nqrKwMtLgQS8I-EOGmdTUUbLA#printMode=true 2/4
7/18/24, 9:32 AM Loops.ipynb - Colab
## pass
## The pass statement is a null operation; it does nothing.
for i in range(5):
if i==3:
pass
print(i)
0
1
2
3
4
## Nested loopss
## a loop inside a loop
for i in range(3):
for j in range(2):
print(f"i:{i} and j:{j}")
## Examples- Calculate the sum of first N natural numbers using a while and for loop
## while loop
n=10
sum=0
count=1
while count<=n:
sum=sum+count
count=count+1
n=10
sum=0
for i in range(11):
sum=sum+i
print(sum)
55
2
3
5
7
11
13
17
19
23
29
https://colab.research.google.com/drive/1Ac9yuG9nqrKwMtLgQS8I-EOGmdTUUbLA#printMode=true 3/4
7/18/24, 9:32 AM Loops.ipynb - Colab
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
keyboard_arrow_down Conclusion:
Loops are powerful constructs in Python that allow you to execute a block of code multiple times. By understanding and using for and while
loops, along with loop control statements like break, continue, and pass, you can handle a wide range of programming tasks efficiently.
https://colab.research.google.com/drive/1Ac9yuG9nqrKwMtLgQS8I-EOGmdTUUbLA#printMode=true 4/4