Python While Loop
Python While Loop
Python While Loop
The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.
1. while expression:
2. statements
Output:
1
2
3
4
5
6
7
8
9
10
Output:
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our
program to run continuously in the loop without any disturbance.
Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")
Output:
Hi! we are inside the infinite while loop
Hi! we are inside the infinite while loop
Example 2
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))
Output:
Example 1
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. else:
6. print("The while loop exhausted")
Example 2
1. i=1
2. while(i<=5):
3. print(i)
4. i=i+1
5. if(i==3):
6. break
7. else:
8. print("The while loop exhausted")
Output:
1
2
In the above code, when the break statement encountered, then while loop stopped its
execution and skipped the else statement.
Output: