The loops in python it allows a you to execute multiple statement or block of code repeatly. the loop is also known as a iteration . means repetitive structure. when you want to print hello in 1000 times but we con't write 1000 times print statement that's why we using loops to execute a block of code in multiple times.
The python provides mainly two types of loops
Let understand by loops
The while loop is a indefinite loop which means the code is execute or iterate as long as condition is true. and the while loop contain conditions to exit the loop or terminate the loop but for loop exit using range() function. when we does not assign the condition it will repeat the process does not end . the while loop evaluate the condition first then execute the body of the loop or statements . if condition is false then the loop was exit
while condition:
statement
i=0
while i<=10:
print(i)
i=i+1
0
1
2
3
4
5
6
7
8
9
10
i=0
while i<10:
print('Hello')# The loop does not end because the i does not increment
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
.........# does not end
The for loop in python it is a Definite loop which means it execute the statements repeatly until the last item reached. This is also used if we have a list of thing to loop through, like sequences that is list, tuple, dict and String . all examples in the below
Here , val accessed each item of sequence on each iteration. loop continues until we reach last item
For val in sequence:
statement
for num in range(1,10,2)
print(num)
1
3
5
7
9
names=["Darshan","Tharun","Hemanth"]
for name in names
print(name)
Darshan
Tharun
Hemanth
tuple=(1,2,3," Darshan ", " Therun", " Hemanth")
for tuples in tuple:
print(tuples)
1
2
3
Darshan
Therun
Hemanth
Dictionary = {
"name": "Darshan",
"age": 19,
"Place": "Kolar"
}
for key, value in Dictionary.items():
print(f"{key}: {value}")
name: Darshan
age: 19
Place: Kolar
The python provides the nested loops which means the python code program has one loop within another loop is called nested loop .Example in the below
for i in range(2, 11):
for j in range(2, 11):
print(f"{i * j:4}", end="")
print()
2 | 4 6 8 10 12 14 16 18 20
3 | 6 9 12 15 18 21 24 27 30
4 | 8 12 16 20 24 28 32 36 40
5 | 10 15 20 25 30 35 40 45 50
6 | 12 18 24 30 36 42 48 54 60
7 | 14 21 28 35 42 49 56 63 70
8 | 16 24 32 40 48 56 64 72 80
9 | 18 27 36 45 54 63 72 81 90
10 | 20 30 40 50 60 70 80 90 100