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:
import random
random_integer = None
while random_integer != 5:
random_integer = random.randint(1, 10)
print(random_integer)
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.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.