Where Can You Use a While Loop?
How to Use Python While Loops- in Practice
As stated earlier, a while loop runs indefinitely if there are no set conditions that stop it. Here is an example of an indefinite while loop:
while 3 < 5: print("It's less than 5")
The condition for the while loop in the code above is 3 < 5.
Now let’s take a look at the while loop code for the herd inspection example from the previous section:
StdTemperature = 37 sheep_temp = 38 while sheep_temp > StdTemperature: print("unhealthy") else: print("healthy")
In the code snippet above, the temperature limit is 37. The sheep_temp variable stores each sheep’s temperature. The while loop keeps outputting “unhealthy” as long as the temperature is above 37; this is the condition for executing the loop in this case. If you change sheep_temp to a value less than 37, it executes the else statement.
However, using a while loop to solve the problem above is too primitive and unscalable. That’s because you need to manually change the value of the sheep_temp variable each time you need to test a sheep. It means it’s difficult to operate it on an array. The solution to that is beyond the scope of this article.
Notwithstanding, that example should give you some insights about what a while statement does in a Python loop.