While Loop in Python


Youtube Live session on Tkinter

The while loop is used to repeatedly execute a block of statements as long as a given condition is True.
i=0
while ( i< 5): 
    print(i)
    i=i+1
While loop with indentation Note that the 2nd line print(i) is placed after an indente of one space. Without that we will get an error asking expectd an indented block . The code to be executed within the block is to be kept with indenting.
The loop will continue as long as the condition is true. We used one incremental variable i to change the condition to match the loop. ( In For loop we have not used any incremental variable )

The output of above code is here
0
1
2
3
4

Python while loop with else break & continue to execute code blocks based on condition True or False


While loop with else

Code wihin else will execute once the loop is over
i=0;
while ( i< 5):
    print(i)
    i=i+1
else:
 print("i am outside the loop")
0
1
2
3
4
i am outside the loop

Break and continue in a while loop

When break statement is encountered the execution comes out of the loop. In case of continue the execution returns to the starting of the loop skipping the rest of the statements ( after continue ) and continues again.

In the codes give below , as soon as break is encountered the execution comes out of the loop, so 3,4 and 5 are not printed. But when continue is used in place of break the printing of 3 is skipped but the loop continues again so 4 and 5 are printed.

You can also observe the else part of the code is not executed once break statement is encounterd and execution comes out of the loop.
While loop break and continue
Using continue
i=0;
while ( i< 5):
    i=i+1
    if(i==3):
       continue
    print(i)
else:
 print("i am outside the loop")
1
2
4
5
i am outside the loop
Using break
i=0;
while ( i< 5):
    i=i+1
    if(i==3):
       break
    print(i)
else:
 print("i am outside the loop")
1
2

Nested while loop

i=j=0
while i<5:
  while j<5:
    print('*',end='')
    j=j+1
  print("")
  j=0
  i=i+1
Output
*****
*****
*****
*****
*****
We can use the j value also by updating this line
print(j,end='')
output
01234
01234
01234
01234
01234

Checking if input number is prime number or not

num=int(input("Enter the number you want to check : "))
i=2
while(i<num/2):
  if(num%i == 0):
    print(num, " is not a prime number")
    break;
  i=i+1
else:
  print(num , " is a prime number")
In above code if the condition checked for if became True for any value of i then the break statement will be executed terminating the while loop and the else part of the code will be skipped.

Display all prime numbers

num=100 # Upper limit of prime numbers 
i=2
while i<=num-1:
  j=2 # start checking each number from 2 
  while j <= i/2 : # check upto half the number 
    if(i%j==0): # reminder of division is 0 
        break  # come out of loop without else part
    j=j+1
  else:
    print(i, " is a prime number") # if break is not encountered 
  i=i+1

Example : Sum of user inputs

Collect user inputs and show the result, user can exit by entering 0 ( zero )
All input() data are string type so we used int() to convert them to integer before adding.
user_input = ""
my_sum=0
while user_input != '0':
  user_input = input("Enter 0 to quit: ")
  my_sum=my_sum + int(user_input)
else:
  print("Exited the loop. The sum :", my_sum)


  • Python Basics : while loop
    21-Feb-2024 quixote
Check all our Live sessions on basics of Python



Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer