Python3 While loop
Python While Loop
output: enter a number 16
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 :
Eg:
lst=[10,20,30,40,50]product=1index=0while index<len(lst):product*=lst[index]index+=1print("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=0while iindex<len(num):print(number[index])index+=1else:print("no item left in the list")
output::
123no 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))
16 is divisible by 216 is divisible by 416 is divisible by 816 is not a prime number
If you have any doubts pls comment
Comments
Post a Comment