Python While Loop

While Loop

While loop executing the code block under it as long as a boolean expression is True. What they do is simply do a test like an if-statement, but instead of running the code block once, they jump back to the “top” where the while is and repeat. It keeps doing this until the expression is False. 

Note:- Here’s the problem with while-loops: Sometimes they do not stop. This is great if your intention is to just keep looping until the end of the universe. Otherwise, you almost always want your loops to end eventually.

Exercise 1:


If we don't use line 7 then a will always be less then or equal to 5. So, this loop will go on forever.

Let's take another example

Exercise 2:


Line 1, We imported 2 of python inbuilt functions called datetime and time (Don't worry about these function we have different chapter covering functions)

Line 4, We printed current date and time

Line 5, the program will go to sleep for 60 seconds. So, this loop will iterate every minute. 

Line 8, In case, if 'i' is greater then 5 then this loop will break.



Try exercise 1 with for loop instead of while loop. See if you need incrementer?


About the author



Please login to comment