Search code examples
pythonif-statementprintingwhile-loopbreak

If statement returning False in While True loop (Python)


I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop. But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break. Why?

i=0
while True:
    if i < 10:
        i = i + 1 
        print(i)

Solution

  • while X repeats when X equals to True so in while True it's always True. It only breaks with break statement. In your code, you only check the value inside the while loop with if so neither you break the while loop nor you change True to False in while True.

    If you want to use while:

    i = 0
    while i < 10:
        i += 1
        print(i)
    

    Or

    i = 0
    while True:
        if i < 10:
            i += 1
            print(i)
        else:
            break
    

    Without while:

    for i in range(10):
        print(i)