问题描述
为什么下面的代码会无限循环? 第一次返回是9 它不再等于 10。 我无法得到它。 有人能简单解释一下吗?
n = 10
while True:
print(n,end=' ')
n = n - 1
print('Done!')
解决方法
while True
永远存在,因为 True
永远是 True
。
如果您想在 n
变为 0
时结束循环,请尝试:
n = 10
while n > 0:
print(n,end=' ')
n = n - 1
print('Done!')
输出:
10 Done!
9 Done!
8 Done!
7 Done!
6 Done!
5 Done!
4 Done!
3 Done!
2 Done!
1 Done!
,
n = 10 # Here you are initializing the variable n as 10
while True: # Now you are saying,while True (this means forever because you are saying,as long True is true,do this)
print(n,end=' ')
n = n - 1
print('Done!')
我相信你想验证 n 等于 10,所以,条件必须改变:
n = 10 # Here you are initializing the variable n as 10
while n = 10: # Now you are saying,while n = 10 (this means only once because the loop changes the value of n)
print(n,end=' ')
n = n - 1
print('Done!')
,
你使用 while True 没有 break 语句 用这个
n = 10
while n>0:
print(n,end=' ')
n = n - 1
print('Done!')
或
n = 10
while True:
print(n,end=' ')
n = n - 1
print('Done!')
if(n==0):
break;