INFINITE LOOP

Repeat a program, forever…!

M. Lim
Intro to Programming
2 min readFeb 16, 2018

--

→ Lab Assignment: “Seasons” in repl.it

The “while” loop

The while loop repeatedly executes whatever code is “nested” (aka indented) below it — as long the while loop’s condition is True.

If we want something to repeat forever, we can just use True (with a capital T) as the condition. This is called an INFINITE LOOP:

Wow, that’s super annoying.

But — this can be really useful for testing inputs!

If you need to test your program with many different inputs, you can temporarily put all your code inside a while True: loop, and then take it out of the loop when you’re done testing.

In the real world, we want to avoid infinite loops, because the only way to end an infinite loop is to kill the program. Plus, an infinite loop can use up all your computer memory and make it crash.

Luckily, there are keyboard shortcuts for indenting and un-indenting many lines at once.

  • To indent: Select all the lines to indent, then press TAB.
  • To un-indent: Select all the lines to un-indent, then press SHIFT + TAB.

Let’s practice by putting some code into a while loop (by indenting), and then taking it out of the loop (and un-indenting). To start, copy + paste this into a new IDLE file:

For today’s lab assignment, you’ll need to test 12 different inputs — so use a while loop!

--

--