Infinite loops

In a while loop, you need to write a condition for the loop to continue to run. However, if you don't handle the condition correctly, it's possible to create an infinite loop. Look at this example, which tries to print out the numbers 0 to 9:

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

But there is a bug here! There is no i += 1 at the end of the loop body, so i will never increase. This means that i < 10 will always be true and the loop will never end. This is called an infinite loop, which can cause your program to freeze. Be cautious when using a while loop!

Breaking out of a loop

Having the condition in your while loop always be True isn't necessarily bad in some situations. Sometimes these loops can simplify program logic and make it easier to understand, but in order for it to not overload your computer, you must have another way for the computer to exit the loop. Let's write a program that repeatedly accepts integers from user input and print out the squares, until the input is 0. Here is the logic in plain English:

Start an infinite loop.
Get user input.
If input is 0, stop the loop.
If input is not 0, do math and continue the loop.

This kind of while loop is infinite:

while True:

In this loop, the condition itself is True, so the computer will always continue running the loop. Now we need a way to exit the loop. This can be done with break keyword. break will cause the current loop to end, and the computer will jump to the code directly following the loop. Here is a good example of an infinite loop that works:

while True:
    n = int(input('Give me an integer: '))

    if n == 0:
        break

    print(str(n) + '*' + str(n) + '=' + str(n*n))

print('done')

Sample output:

5*5=25
9*9=81
6*6=36
done

In this example, the computer will continue running the code until the user gives it an input of 0.

Note: if you have nested loops (loop inside another loop), break only exits the loop it directly resides in, and the code continues in the outer loop.

results matching ""

    No results matching ""