Definition
Python while loop is used to execute a block of code until the given condition is True.
Syntax
while condition: # block of code # to be executed # until the condition is True
Examples
Example1
i = 5 while i>0: print(i) i = i - 1
Output
5 4 3 2 1
Example2
# printing table for any number number = int(input("Enter number:")) i = 1 while i!=11: print(number, "X", i, "=", i*number) i=i+1
Output
Enter number:10 10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100
Example3
# infinite while loop while True: print("This line will print infinite times")
Output
This line will print infinite times This line will print infinite times This line will print infinite times This line will print infinite times This line will print infinite times ... ... ...
break statement
We can use break statement if we want to exit the while loop.
Generally, we use break statements in while loop when we have some specific conditions to exit the while loop.
Example1
i = 0 while True: print(i) if i==5: break i = i + 1
Output
0 1 2 3 4 5
Example2
# printing table i = 1 number = 10 while True: if i==11: break print(f"{number} X {i} = {number*i}") i = i + 1
Output
10 X 1 = 10 10 X 2 = 20 10 X 3 = 30 10 X 4 = 40 10 X 5 = 50 10 X 6 = 60 10 X 7 = 70 10 X 8 = 80 10 X 9 = 90 10 X 10 = 100
If you have any confusion in the 7th line about f, then click here. Scroll down on that page and read fast string concepts.
continue statement
Unlike the break statement, continue statement skips one step of the loop and continues with the next step.
Example1
i = 0 while i<6: i=i+1 if i==2: continue print(i)
Output
1 3 4 5 6
Example2
# skipping every step i = 0 while i<6: i=i+1 continue print(i)
Program outputs nothing
while… else…
In python, we can use else statement with while loop.
Block of else statement will be executed every time unless the while loop is terminated with a break statement.
Example1
i = 0 while i<6: i=i+1 print(i) else: print(i)
Output
1 2 3 4 5 6 6
Example2
i = 0 while i<6: i=i+1 print(i) if i==4: break else: print(i)
Output
1 2 3 4
Auto Login with Python
So today we will learn how to auto login in a tab using Python. So, let’s first see…
Adding three matrices in Python
In python, it’s very easy to deal with matrices due to its simple syntax and we create matrices…
Simple Music Player Using Python
Hello friends, do you know that there are many ways to make music players from simple to advanced…
Changing Screen Size: Tkinter
Hello guys welcome again to our site where you get amazing source code absolutely free with explanation So,…
GUI Age Calculator
Hello friends, today we will make an age calculator using python’s GUI library tkinter so, let’s start. Python…
Displaying Images in tkinter
Hello guys, as usual we are sharing one more source code using which you can display images inside…