Skip main navigation

Do this forever

Some instructions in a program should repeat "forever". Read this article by Martin O'Hanlon to find out how to do this in Python.
A cartoon illustration of a robot spinning around

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.

This article is from the free online

Programming 101: An Introduction to Python for Educators

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now