INFINITE LOOP
Repeat a program, forever…!
→ 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:
while True:
response = input("I know you are but what am I? ")
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:
x = int(input("I bet I can tell you whether an integer is negative, zero, or positive. Go ahead, tell me an integer: "))if x < 0 :
print(x,"is negative.")elif x == 0 :
print(x,"is zero.")else :
print(x,"is positive.")