Python Programming

While Loop in Python

In Programming, Python by Baqir Ali

While loop is a loop that keeps iterating or repeating until the condition is false. We use while loop when the number of repetitions is unknown to us.

Example code of while loop in Python

i=1;
while i<=10:
    print(i)
    i+=1

Output:

1
2
3
4
5
6
7
8
9
10

Whenever we want to create a loop dependent upon the user input we use a while loop for that. In the following, while loop condition, it repeats the statements until the ‘char’ value is ‘y’ whenever the user inputs a character other than ‘y’ the loop stops.

char='y'
while char=='y':
    print("--- TO BE REPEATED EACH TIME ---",end='')
    char=input("Do you want to repeat? ")
print("End of the line")

Output:

— TO BE REPEATED EACH TIME —Do you want to repeat? y
— TO BE REPEATED EACH TIME —Do you want to repeat? y
— TO BE REPEATED EACH TIME —Do you want to repeat? y
— TO BE REPEATED EACH TIME —Do you want to repeat? y
— TO BE REPEATED EACH TIME —Do you want to repeat? y
— TO BE REPEATED EACH TIME —Do you want to repeat? y
— TO BE REPEATED EACH TIME —Do you want to repeat? n
End of the line

Support us by sharing this post