What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don’t know beforehand, the number of times to iterate.
Syntax:
while test_expression:
Body of while
In while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True.
After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
Body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
While loop
Example: print nos from 1 to 10
Sol:
i=1 while(i<=10): print(i) i=i+1
Output:
1
2
3
4
5
6
7
8
9
10
>>>
Example: print nos from 1 to 10 in reverse order
Sol:
i=10 while(i>=1): print(i) i=i-1
Output:
10
9
8
7
6
5
4
3
2
1
>>>
Example: print all even nos upto 20
Sol:
i=2 while(i<=20): print(i) i=i+2
Output:
2
4
6
8
10
12
14
16
18
20
>>>
Example: print all odd nos upto 35
Sol:
i=1 while(i<=35): print(i) i=i+2
Output
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
>>>