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:
      lets_play_tennis()
  • 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

var=5
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.

flag=True
while flag:
    print("Flag is True")
    flag=False

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

flag=1
while flag:
    print("Flag is True")
    flag-=1

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

a=3
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")
    else:
        print("Number",num,"is an odd number")
    num-=1
   
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.

num=1
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: "))
 
odd_count=0
even_count=0
 
while var!=0:
    if var%2 ==0:
        even_count+=1
    else:
        odd_count+=1
   
    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

list=['easy.','very','is','Python']
index=len(list)
 
while index:
    print(list[index-1],end=' ')
    index-=1

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: "))
var=1
sum=0
while var<=n:
    sum+=var
    var+=1
   
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: "))
 
lar_num=0
 
while num!=0:
    if num>lar_num:
        lar_num=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

lucky_num=15
 
guess=int(input("Enter your guess number: "))
guess_count=0
 
while guess!=lucky_num:
    guess_count+=1
    if guess>lucky_num:
        print("Your guess is greater than my lucky number.")
    else:
        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

i=5
while i>=1:
    print(i)
    i-=1
else:
    print(i)

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:

i=2
while i>=0:
      print(i)
      i-=1
else:
      print(i)
else:
      print(i)

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

Learn more on Python: https://realpython.com/

Leave a Reply

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

Python 3.11.1 Features