
Python 学习笔记
新手最容易写出的死循环
理解 while 循环为何停不下来,并学会让停止条件真正能够发生。
Python 学习笔记
新手最容易写出的死循环
理解 while 循环为何停不下来,并学会让停止条件真正能够发生。
Your program keeps printing the same number, the terminal will not stop, and everything seems frozen. Python is probably fine. You have likely created an infinite loop.
The most common beginner mistake is simple: the while condition stays True, and nothing inside the loop can make it become False.
The Most Common Mistake
This code is supposed to print 1 through 5:
count = 1
while count <= 5:
print(count)
Instead, it keeps printing 1. The condition count <= 5 is true, but count never changes. Every new check produces the same result.
Fix It by Updating the Control Variable
Add count += 1 inside the loop:
count = 1
while count <= 5:
print(count)
count += 1
Now count eventually becomes 6, making count <= 5 false. The loop stops naturally.
The real rule is not simply “always add one.” Something inside the loop must change the state so that the stopping condition can eventually be reached.
Another Trap: Resetting Inside the Loop
Sometimes an update is present, but the variable is reset on every iteration:
count = 1
while count <= 5:
count = 1
print(count)
count += 1
At the beginning of every iteration, count = 1 sends the value back to its starting point. Initialization usually belongs before the loop, where it runs once. The loop body should move the state forward.
User Input Must Be Updated Too
The same mistake can happen without a counter:
answer = input("Type quit to stop: ")
while answer != "quit":
print("Still running")
If the first answer is not quit, the program never asks again. The value controlling the condition cannot change.
Read new input inside the loop:
answer = input("Type quit to stop: ")
while answer != "quit":
print("Still running")
answer = input("Type quit to stop: ")
The controlling value is now user input instead of a counter, but the principle is exactly the same.
The Three-Question Check
After writing a while loop, ask:
- Condition: what must be true for the loop to continue?
- Update: which line inside the loop changes that condition?
- Stop: when will the condition become false?
Consider this example:
number = 1
while number < 100:
number *= 2
print(number)
The condition is number < 100. The update is number *= 2. The loop stops when number reaches or passes 100.
If you cannot answer one of these three questions, inspect the loop again before running it.
Is while True Always Wrong?
No. while True intentionally creates an endless loop, but break can provide a clear exit:
while True:
answer = input("Type quit to stop: ")
if answer == "quit":
break
This can be useful in interactive programs. Make sure the break is reachable and the exit condition is clear.
Practice
- Explain why
while score < 10: print(score)cannot stop. - Change an input loop so that it stops when the user enters a blank string.
- Challenge: write a
whileloop that counts down from 10 to 1, then identify the line that eventually makes its condition false.
One-Sentence Takeaway
When you write a while loop, find the step inside it that will eventually make the condition false.
程序一直打印同一个数字,终端停不下来,甚至看起来像“卡住了”。这往往不是 Python 坏了,而是你写出了一个死循环,也叫 infinite loop。
初学者最常见的原因很简单:while 的条件一直是 True,而循环里面没有任何代码能让它变成 False。
最常见的错误
下面的代码想打印 1 到 5:
count = 1
while count <= 5:
print(count)
但它会一直打印:
1
1
1
...
程序先检查 count <= 5。因为 count 是 1,条件为 True,所以进入循环。可是循环里只打印了 count,没有改变它。下一轮检查时,count 仍然是 1,条件当然还是 True。
修复方法:更新控制变量
给循环加入 count += 1:
count = 1
while count <= 5:
print(count)
count += 1
输出:
1
2
3
4
5
现在每次循环都会让 count 增加 1。当它变成 6,条件 count <= 5 就是 False,循环自然停止。
关键不只是“记得加一”,而是确保循环里有某种变化,会让停止条件最终成立。
另一个陷阱:在循环里重置变量
有时同学写了更新语句,程序还是停不下来:
count = 1
while count <= 5:
count = 1
print(count)
count += 1
每轮开始时,count = 1 都会把变量重置。循环末尾虽然把它加到 2,下一轮又立刻回到 1,所以条件永远无法变成 False。
初始化通常应该放在循环外,只运行一次:
count = 1
while count <= 5:
print(count)
count += 1
循环外负责设置起点,循环内负责推进状态。
用户输入也需要更新
while 经常用来等待用户输入特定内容。下面的程序也会无限重复:
answer = input("Type quit to stop: ")
while answer != "quit":
print("Still running")
如果第一次输入的不是 quit,循环里没有再次读取输入,answer 就永远不会改变。
正确写法是在循环里更新 answer:
answer = input("Type quit to stop: ")
while answer != "quit":
print("Still running")
answer = input("Type quit to stop: ")
这里控制循环的不是计数器,而是用户输入。但原则完全相同:控制条件的值必须有机会改变。
三步检查法
每次写完 while,都检查三件事:
- 条件:什么条件为
True时继续? - 更新:循环里的哪一行会改变这个条件?
- 停止:在什么情况下,条件会变成
False?
以这个例子为例:
number = 1
while number < 100:
number *= 2
print(number)
- 条件是
number < 100。 - 更新是
number *= 2。 - 当
number达到或超过 100 时停止。
如果这三个问题中有一个答不上来,就先不要运行代码,重新检查循环结构。
while True 一定是错误吗?
不一定。while True 会主动创建一个无限循环,但可以用 break 在明确的位置退出:
while True:
answer = input("Type quit to stop: ")
if answer == "quit":
break
这种写法在某些交互程序里很方便。不过初学阶段要确保 break 确实能够执行,并且退出条件清楚。否则它就会成为真正停不下来的循环。
小练习
- 找出下面代码不能停止的原因:
while score < 10: print(score)。 - 修改一个输入循环,让用户输入空字符串时停止。
- 挑战题:写一个从 10 倒数到 1 的
while循环,并说明哪一行让条件最终变成False。
一句话记住
写 while 时,不只要看开始条件,还要找到循环里让条件最终变成 False 的那一步。
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。
有问题或建议?
如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。