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

Our purpose is to transform access to education.

We offer a diverse selection of courses from leading universities and cultural institutions from around the world. These are delivered one step at a time, and are accessible on mobile, tablet and desktop, so you can fit learning around your life.

We believe learning should be an enjoyable, social experience, so our courses offer the opportunity to discuss what you’re learning with others as you go, helping you make fresh discoveries and form new ideas.
You can unlock new opportunities with unlimited access to hundreds of online short courses for a year by subscribing to our Unlimited package. Build your knowledge with top universities and organisations.

Learn more about how FutureLearn is transforming access to education