Instead of writing the same code multiple times we use loop statement to execute group of statements several times. The loop statement will execute until satisfying the given condition.
Python provides the following types of loops,
|while loop||While loop repeats a statement or |
group of statements as long as a
condition is true.
|for loop||The for loop is a control flow statement, |
which allows code to be executed repeatedly.
|nested loops||When we use a loop inside any other |
for loop or while loop then it is a nested loop.
While loop will execute a block of statement repeatedly until the given condition satisfies. The while loop consists of a condition block and it will keep on executing the statement until the condition becomes false.
while expression: statement
i = 0 while i < 5: print(i, "is less than 5") i = i + 1
0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5
The else statement will execute when the while condition becomes false.
i = 0 while i < 5: print(i, "is less than 5") i = i + 1 else: print(i, "is greater than 5")
0 is less than 5 1 is less than 5 2 is less than 5 3 is less than 5 4 is less than 5 5 is greater than 5
The break statement is used to stop the while loop even if the condition is true.
i = 0 while i < 10: print(i, "is less than 10") if i == 5: break i = i + 1
0 is less than 10 1 is less than 10 2 is less than 10 3 is less than 10 4 is less than 10 5 is less than 10
The continue statement is used to skip the current iteration, and continue with the next.
i = 0 while i < 5: i = i + 1 if i == 2: continue print(i)
1 3 4 5
for loop is used to execute a set of statements each item in the sequence, that is either a list, a Dictionary, a set or a string.
for iterating_var in sequence: statements
num = [1, 2, 3, 4, 5, 6, 7] for i in num: print(i)
1 2 3 4 5 6 7
Range function returns a sequence of numbers it starts with o and increase by 1 until the special number is reached.
for i in range(5): print(i)
0 1 2 3 4
Python allow us to use one loop inside another loop.
Nested for loop
The general syntax for for loop is,
for iterating_var in sequence: for iterating_var in sequence: statements statements
for i in range(1, 8): for j in range(i): print("#",end=' ') print()
# # # # # # # # # # # # # # # # # # # # # # # # # # # #
Nested while loop
The general syntax for nested while loop is,
while expression: while expression: statement statement
a = 1 while(a <= 2): b = 1 while(b <= 2): print(b) b = b+1 print("\n") a = a + 1
1 2 1 2
Get real time update about this post categories directly on your device, subscribe now.