#While Loop Statement #A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true.
#Syntax of while loop :-#while expression:#statement(s)#Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true.
# Example:-c =1while c <=10:print("Hello World!") c = c +1print("Python is Awesome")
num =int(input("Enter number : "))c =1while c <=10:print("{:5}\tx{:5}\t={:5}".format(num,c,num*c)) c = c +1
Enter number : 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
Example 12:
from random import randrangewhileinput("Do want to roll again : "):print("Score : ",randrange(1,7))
Do want to roll again : 5
Score : 3
Do want to roll again : 2
Score : 2
Do want to roll again :
Example 13:
num =int(input("Enter a Number : "))if num <=1:print("Not Prime")print("Error!This is not valid input to check prime")exit(0)elif num <=3:print("Prime")exit(0)check =2while check <= num //2+1: k = num % check if k ==0:print("Not Prime")breakelif check == num //2+1:print("Prime") check = check +1
Enter a Number : 55
Not Prime
Example 14:
#Fibbonacci Series using While Loopnum =int(input("Enter the no of terms"))x =0y =1a =0while a < num: z = x + y x = y y = z a = a +1print(z)
Enter the no of terms5
1
2
3
5
8
Example 15:
#Rock, Paper, Scissor game using while loop(2 Players)p1 = [ ('r','s'),('p','r'),('s','p')]from getpass import getpasswhileTrue: ch1 =getpass("Player1: ") ch2 =getpass("Player2: ")if ch1 == ch2 :print("Match Tie")elif (ch1,ch2) in p1 :print("Player1 is the Winner")else:print("Player2 is the Winner") ch =input("Do want to continue (y/n) : ").strip().lower()if ch =='y'or ch =='yes':continueelse:break
Player1: p
Player2: r
Player1 is the Winner
Do want to continue (y/n) : n
Example 16:
##Rock, Paper, Scissor game using while loop(1 Player)p1 = [ ('r','s'),('p','r'),('s','p')]from random import choicewhileTrue: ch1 =choice(['r','p','s']) ch2 =input("Player2: ")if ch1 == ch2 :print("Match Tie")elif (ch1,ch2) in p1 :print("Computer Choice was : ",ch1)print("Player Choice was : ",ch2)print("Player1 is the Winner")else:print("Computer Choice was : ",ch1)print("Player Choice was : ",ch2)print("Player2 is the Winner") ch =input("Do want to continue (y/n) : ").strip().lower()if ch =='y'or ch =='yes':continueelse:break