Python while loop allows you to repeatedly execute a block of code as long as a specified condition is true. This is a logic control iteration.
Python while loop Syntax
While condition:
# Code to execute if the above condition is true
Example 1
To print 1 to 5 numbers
x=1
while x<=5:
print(x)
x=x+1
if x=x+1 is not there, this python while loop becomes infinite loop. That means it never ends.
Example 2
To print 1 to 5 odd numbers
x=1
while x<=5:
print(x)
x=x+2
Example 3
To print 1 to 5 even numbers
x=2
while x<=5:
print(x)
x=x+2
Example 4
To print 1 to 5 numbers total
x, sum=1,0
while x<=5:
sum=sum + x
x=x + 2
print(sum)
Example 5
To print even numbers. The system will only stop when the user enters an odd number.
x=int(input("Enter a number :"))
rem=x mod 2
while rem != 1:
print(x)
x=int(input("Enter a number :"))
rem=x mod 2
Example 6
Ask user to enter 10 numbers. Program will displays the number only if the number is an odd number.
x=1
while x<=10:
num=int(input("Enter a number :"))
rem=num mod 2
if rem == 1:
print(num)
x=x + 1
Example 7
Input 10 numbers, and print their total – but any numbers>100 should be ignored, i.e should not be summed.
x,tot=1,0
while x<= 10:
num=int(input("Enter a number :"))
if num<=100:
tot=tot + num
x=x+1
print(tot)