[英]If statement returning False in While True loop (Python)
I expected that in this If statement, the variable 'i' would increment until it eventually equals 10, and subsequently 'if 10 < 10' would return False, breaking my while loop.我希望在这个 If 语句中,变量 'i' 会递增,直到它最终等于 10,随后 'if 10 < 10' 将返回 False,从而打破我的 while 循环。 But this code seems print until 10 and then get stuck in an infinite loop unless I add an else: break.但是这段代码似乎打印到 10 点,然后陷入无限循环,除非我添加 else:break。 Why?为什么?
i=0
while True:
if i < 10:
i = i + 1
print(i)
while True
will make the loop run forever because "true" always evaluates to true. while True
将使循环永远运行,因为“true”总是评估为 true。 You can exit the loop with a break.您可以通过中断退出循环。
To achieve what you want to do, I would use为了实现你想做的事情,我会使用
while i < 10:
print (i)
i++
while X
repeats when X
equals to True
so in while True
it's always True
.当X
等于True
时while X
重复,所以在while True
中它总是True
。 It only breaks with break
statement.它只用break
语句中断。 In your code, you only check the value inside the while
loop with if so neither you break the while loop nor you change True
to False
in while True
.在您的代码中,您仅使用 if 检查while
循环内的值,因此您既不会中断 while 循环,也不会在while True
中将True
更改为False
。
If you want to use while
:如果你想使用while
:
i = 0
while i < 10:
i += 1
print(i)
Or或者
i = 0
while True:
if i < 10:
i += 1
print(i)
else:
break
Without while
:没有while
:
for i in range(10):
print(i)
That is because there isn't anything telling you to terminate the loop.那是因为没有任何东西告诉你终止循环。 So it will continue even after the if statement isn't satisfied.所以即使在 if 语句不满足之后它也会继续。
This is why it is generally not a great practice to use while True
这就是为什么while True
时使用通常不是一个好习惯的原因
You can achieve the same thing with a for loop when the break condition is built into the loop:当 break 条件内置到循环中时,您可以使用 for 循环实现相同的目的:
for i in range(0, 10):
print(i)
If you want to use while True then you can go for:如果你想使用 while True 那么你可以 go 用于:
i=0
while True:
i = i + 1
print(i)
if i == 10:
break
I think you need to understand a few things here, as you have set while True
which means statement will never gets false
so there is never end to while loop
even if if condition
gets fail.我认为您需要在这里了解一些事情,因为您设置了while True
这意味着语句永远不会为false
,因此即使if condition
失败, while loop
也永远不会结束。 So the while loop
will continue running till you interrupt.因此, while loop
将继续运行,直到您中断。
The only way you can achieve this without break is like this, where you have a variable which will reset the condition of while loop
to false when if loop
fails你可以在没有中断的情况下实现这一点的唯一方法是这样的,你有一个变量,当if loop
失败时,它会将while loop
的条件重置为 false
i=0
condition = True
while condition:
if i<10:
i=i+1
print(i)
else:
condition=False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.