Python3 While loop

Python While Loop


 WHILE Loop :

              The while loop in python is used to iterate over a block of code as long as the test expression(condition) is true

Syntax::
 
         while test_expression:

                body of while

 


 * The body of the loop is entered only if the test_expression is true.
 * After one iteration, the test_expression is checked again.
 * This process proceeds until the test_expression is false.

Flow Chart :


while Loop in Python programming



Eg:

       lst=[10,20,30,40,50]
       
       product=1
       index=0

       while index<len(lst):
              product*=lst[index]
              index+=1

       print("Product is:{}".format(product))

   
 output:   Product is 14400000


While loop with else:

       This is same as for loop, we can use else block with while loop as well.

* The else part is executed if the condition of while loop evaluates to false. The while loop can be terminated with the break statement.

* In such case ,this is ignored. Hence, a while loop's else part runs if no break occurs and the condition is false.


Eg:

       num=[1,2,3]
       index=0
       while iindex<len(num):
             print(number[index])
             index+=1
       else:
             print("no item left in the list")

 output:: 
               1
               2
               3
               no item left in the list

Program to check given number is prime or not:

       num= int(input("enter a number:")

       isdivisible=False;

       i=2;
       while i<num:
              if num % i==0:
                   isdivisible=True;
                  print("{} is divisible by {}".format(num,i))
             i+=1;
       if isdivisible:
           print("{} is not a prime number" .format(num))
       else:
            print("{} is a prime number" .format(num))

 output:        enter a number 16
               16 is divisible by 2
               16 is divisible by 4
               16 is divisible by 8
               16 is not a prime number



If you have any doubts  pls comment



 

Comments

Popular posts from this blog

Python3 Function Arguments

Python3 File Handling

Python3