Best Laptop
Python while loop

Python while loop

In this Python Tutorial, we will see the use of Python while loop. But before that lets ask what exactly is loop and why do we need it. Loop is something which performs some activity as long as you want it to be done. For example, if we want to play tennis if it’s not raining outside, then we may write something like this:

while its_not_raining_outside:
  • Indentation rules work here just like if-else statement we saw in previous session.
  • If we want to use more than one instruction in while loop, put those instruction at same level of indentation
  • The syntax is easy – put while keyword, then use the condition to be checked followed by colon
  • Then use the indentation and put the instruction that you want to execute if the condition return True

By looking at the above code, you will see that it looks like if statement with only difference is that we have used ‘while’ in place of ‘if’. But that’s not the only difference. See the table below:

Statement/loopCondition returns TrueCondition returns False
If-elseDo the job oncedo the job provided in else statement
WhileDo the job as long as the condition returns Trueskip the while loop
for loopDo the job for as many times you want the job to be doneskip the for loop

FAQ-Python while loop

What is while loop in Python ?

A while loop enables you to iterate over a piece of code again and again till the condition mentioned in the while statement returns True.

How do you use a while loop in Python ?

TO use while loop, first write the keyword while followed by the condition to test and then colon. After this mention the instruction to iterate if the condition is True.

When we should use while loop ?

We should use while loop when we want to iterate over some instruction until our condition is true. Here we may not know how many times we are going to iterate over the instruction.

Are while loop and for loop interchangeable ?

No, they are not interchangeable. for loop is used when we know how many times we have to iterate over some instruction. But while loop is used to iterate as long as some condition is true

How many else statements can be used with while loop ?

We should use only one else statement with while loop. Ideally for every else statement, there has to be one immediate preceding if, elif, while or for loop.

Let’s now see how to use Python while loop:

1. Python while loop to print numbers – This simple program will print integers

while var != 0:
      print(“Number is: “, var)
      var = var -1
print(“While loop is completed”) 

2. Boolean value in while loop – the code enters while loop when the condition returns True/non-zero value.

while flag:
    print("Flag is True")

3. using numeric value in while loop – here we have directly assigned value 1 to flag.

while flag:
    print("Flag is True")

4. putting while loop instruction on same line – just like if statement, if there is just one instruction inside while loop, we can put it on the same line where while is mentioned. If there are multiple instructions, then separate them by semicolon like below

while a: print(a); a-=1

5. while loop to check odd and even numbers – Here in the while condition I have just used ‘while num’. This will work since while condition will be True till the value of num reached 1. When num becomes 0, while will return False and while loop will be skipped

num = 10
while num:
    if num%2==0:
        print("Number",num,"is an even number")
        print("Number",num,"is an odd number")
print("Job done")

Note: In both the above examples, we have used a statement to ensure that while loop gets completed, like var = var -1 and num-=1. If we don’t used such instruction, then while loop will become an infinite loop and will never end

6. Infinite while loop – This will infinitely print the statement since we have not provided a statement to end the loop. In this case you have to press CTRL+C to terminate the program.

while num:
      print(“Number is:”, num)

7. Counting of odd and even numbers – Here we will write a program to prompt user to keep entering numbers and the program will count the number of odd and even numbers. The program will continue till the user enter numbers. To stop entering more numbers and get the result, enter 0. Here we are assuming that user will enter only numbers and not strings. We will see how to handle such inputs later.

var=int(input("Enter a number: "))
while var!=0:
    if var%2 ==0:
    var=int(input("Enter a number: "))
print("Count of even numbers entered is:", even_count)
print("Count of odd numbers entered is:", odd_count)

8. Reading list in while loop – here we have defined a list and taken its length in a variable. Then using while loop, we are printing the elements of the list till there are no more elements, i.e., when index reached less than 0

while index:
    print(list[index-1],end=' ')

9. While loop to get sum of first n integers – here we will ask user to enter an integer and then we will get the sum of first n integers

n=int(input("Enter a number to get sum: "))
while var<=n:
print("Sum of first",n,"numbers is: ",sum)

10. While loop to get the largest number entered by user – here we are asking the user to enter the numbers and then we are comparing the numbers to get the largest number. To exit the loop, user needs to enter 0 and then we will display the largest number

num=int(input("Enter a number: "))
while num!=0:
    if num>lar_num:
    num=int(input("Enter a number: "))
print("Largest number entered is: ",lar_num)

11. while gaming – Let’s code a very simple game to guess the number. Imagine that you have thought your lucky number in your mind and asking your friend to guess the number you thought. Your friend will keep guessing the number till he gives the correct answer. Now you have to tell how many tries he did to guess the correct number. You are also helping your friend by giving him some hints

guess=int(input("Enter your guess number: "))
while guess!=lucky_num:
    if guess>lucky_num:
        print("Your guess is greater than my lucky number.")
        print("Your guess is smaller than my lucky number.")
    guess=int(input("Enter your guess number: "))
print("Your guess is now correct. You took",guess_count+1,"chances to guess my lucky number")

12. Using else with while loop – In this program, the else will be executed always at the end of while loop. As soon as the value of i reached 0, while loop is completed and the control goes to else which prints the value of i = 0

while i>=1:

13. We should not use more than one else statement with while loop – Every else must be associated with a preceding if, elif, while, for loop. Any else with no preceding loop will throw error like below:

while i>=0:

Try out more programs of this type to enhance your understanding of while loop in Python.

Learn more on Python:

Leave a Reply

Your email address will not be published. Required fields are marked *

Python 3.11.1 Features