Python While Loop

In the previous article, you learned about the different types of for-loops. The python while-loop can do everything that a for-loop does. However, the for-loop is used when the number of iteration is already known.

Advertisements

In this article, we will explore the while loop and know how to use it in out program.

While Loop Syntax

To create a while loop make sure that you follow the syntax. There are three steps to it.

  1. Initialize the loop variable
  2. Set terminating conditions for the loop variable
  3. increment the loop variable

Let us see an example of while loop below.

# Initialize the loop variable
x = 1
# Set condition that will terminate the loop
while x <= 10:
   print(x)
# Increment the loop for next iteration
   x = x + 1

In the above code the x will print for 10 times and when x == 11 the while condition becomes false and loop terminates. See the output below.

========= RESTART: C:/Python_projects/While_Loop_3.py ================
1
2
3
4
5
6
7
8
9
10
>>> 

Infinite Loop

There is nothing that the while loop which for-loop does. However, you must be careful with the infinite loop which in you program.

Advertisements

An infinite loop is created due to wrong conditions in the while loop which cause the loop to run infinitely.

Consider following example.

# Do not try to run this code 
i = 0
while i >= 0:
   print(i + 3)
   i = i + 1

The syntax in the above code is correct, however, this code will run forever because incorrect terminating conditions., the x will always be greater than 0 and the loop will continue to print values.

Example: Python While Loop

In this example program we are going to keep adding numbers until the number is not equal to 99. After the number becomes 99, the program prints the sum of all the previous numbers.

sum = 0
myNum = 0
while myNum != 99:
     myNum = int(input("Enter your Number: "))
     sum = sum + myNum
print(sum)

Note that the input value is a string and we need to convert it to another type such as integer. Here we use the function called int()

Output of the above program is given below.

========== RESTART: C:\Python_projects\While_Choice_Sum.py ==============
Enter your Number: 44
Enter your Number: 66
Enter your Number: 77
Enter your Number: 45
Enter your Number: 77
Enter your Number: 99
408
>>> 

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.