Python While Loop



Python While

For , If and While are the primitive compound statements/loops in  Python. In this tutorial, we will be covering only the Python while statement.

Table of Contents

Python While Loop:

Python while loop is used to execute a set of statements as long as the condition is true. The below code prints the numbers from 1 to 10.

a=1
while(a<=10):
  print(a)
  a+=1
print("Numbers 1 to 10 are printed")

The above code works as below:

  • Initializing variable a to 1
  • While statement checks if the variable ‘a’ is less than or equal to 10
  • If the condition is True, ‘a’ will be incremented by 1.
  • When the last line has encountered, the condition of the while statement will be tested again.
  • So the above code prints all the numbers from 1 to 10.
  • When ‘a’ becomes 11, the condition becomes false and the loop will be exited.
  • Whatever the statement was written outside the while loop will be executed.

Infinite loop:

We have to be careful about the infinite loop while using the Python ‘while’ statement. In case, we forgot to increment the variable ‘a’, it will result in an infinite loop.

a=1
while(a<=10):
  print(a)
print("Numbers 1 to 10 are printed")

Python While and ELSE:

With the else statement we can run a block of code once when the condition given in the while statement becomes false.

a=11
while(a<=10):
  print(a)
  a+=1
else:
  print("a is greater than 10")

Looping through Lists:

We can loop through lists, strings, and tuples using the while loop.

l=[8,9,1,4,5]
length=len(l)
i=0  # since the index starts with zero
while(i<length):
  print(l[i])
  i+=1

IF inside while loop:

We can also use the IF loop inside the while loop. The below code is to print the even numbers from 1 to 10.

a=1
while(a<=10):
  if a%2==0:
    print(a)
  a+=1

You can modify the above code to print the odd numbers. Try more examples on while loops.