While loop in Python

Hello friends how are you, today in this blog i will teach you what is while loop, syntax of while loop , how while loop works and many programs using while loop in a very simple way. 

Let's start

Syntax of while loop:
while condition:
    body of loop
  • It's body will execute until the given condition is true.

i=1
while i<=10:
    print(i)
    i=i+1
/*
1
2
3
4
5
6
7
8
9
10
*/

/*
factorial of 5=1x2x3x4x5
factorial of 6=1x2x3x4x5x6
factorial of N=1x2x3x....xN
*/
i=1
fact=1
no=int(input("Enter any number:"))
while i<=no:
    fact=fact*i
    i=i+1
print("Factorial of ",no," is ",fact)
/*
Enter any number:6
Factorial of  6  is  716
*/
  • When the condition of while fails then the else part is executed.

i=1
while i<=5:
    print(i)
    i=i+1
else:
    print("This is else part")
/*
1
2
3
4
5
This is else part
*/

i=1
while i<=5:
    if i==3:
        break
    print(i)
    i=i+1
else:
    print("This is else part")
/*
1
2
because when i will become 3
break will terminate the loop
*/

str="Easy"
i=0
while i < len(str):
    print(str[i])
    i=i+1
/*
E
a
s
y
*/


girls=["Ritu","Ajeeta","Sonali"]
i=0
while i < len(girls):
    print(girls[i])
    i=i+1
/*
Ritu
Bulbul
Sonali
*/

Request:-If you found this post helpful then let me know by your comment and share it with your friend. 
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all. 

If you have not subscribed my website then please subscribe my website. 

Try to learn something new and teach something new to other. Thanks.

Post a Comment

0 Comments