In this tutorial we are going to learn :

  • While Loops
  • Infinite Loops 

 

 

While Loops

 

We use while loops to iterate over a set of code as long as a condition is True.

Example:

If our number variable is bigger than 0,  we print the number variable by dividing it by 2. This iteration continues until our condition is True

number = 200

while number > 0:
    print(number)
    number //= 2 

 

Example :

In this program, we get command from the user and if the user type ” done” iteration will
over.

  • Important note here : User can type “Done ” , “done” , “DONE” etc. So we have to be careful about keyword sensitive. Because of that, we used the lower() function to convert all text to lower case
command = ""

while command.lower() != "done":
    command = input("Enter : ") 

 



Infinite Loops


There is a better way to write our program with an infinite loop.

Example :

  • We set the while condition is True.
  • We get data from the user and then the if condition is True we break the program.
while True:
    command = input("Enter :")
    print(f"You entered : {command} ")
    if command.lower() == "done":
        break 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments