Want to keep learning?

This content is taken from the Raspberry Pi Foundation & National Centre for Computing Education's online course, Programming 101: An Introduction to Python for Educators. Join the course to learn more.
A cartoon illustration of a robot spinning around

Do this forever

Using a while loop you can get a computer to continue to do the same task forever, known as an infinite loop. This special type of conditional loop can be really useful, but it’s also a really easy way to use up all of your computer’s processing power!

  • Create a new program, add this code, save it as infinite, and run it.
while True:
    input("press enter")

It doesn’t matter how many times you press the enter key, the program will keep running forever. It will never leave the while loop – it is infinite.

Tip: If you want to end an infinite program click the Stop button on Mu or Trinket.

while True: is the “usual” way of creating an infinite loop in Python and although it looks a bit strange, it makes sense when you understand whats happening.

First consider this program:

keep_running = True
while keep_running == True:
    input("press enter")

The variable keep_running will always be equal to True and as it is never changed to False this program will run forever and is infinite.

If keep_running is always True the same program could be written as follows replacing the keep_running variable with True:

while True == True:
    input("press enter")

As you learnt in week 2, if you were to evaluate True == True it will always be equal to True, so if you replace True == True with True and you end up with:

while True:
    input("press enter")

Reflect: In what sort of situations do you think an infinite loop might be useful? Give an example in the comments.

Share this article:

This article is from the free online course:

Programming 101: An Introduction to Python for Educators

Raspberry Pi Foundation