import random # This loop will run forever unless we break it while True: # Generate a random int between 1 and 10 random_integer = random.randint(1, 10) print(random_integer) # Stop the loop if the random int is 5 if random_integer == 5: break
The while True part is the condition. It checks if True is True. That is always the case. John is always John. So the while loop will run eternally unless it encounters a break statement. You could also rewrite the above Python code to this and it would do the same thing:
random_integer = None
while random_integer != 5:
random_integer = random.randint(1, 10)
This time we directly check the condition using the while-statement instead of the if-statement. This version of the code is shorter, but the previous version offers more flexibility since you can add other elif-else blocks of code inside the while loop if necessary.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.