干杯,我的问题是我不知道如何在多种情况下做一段时间。我真的不明白为什么这不起作用:
import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
v = random.randint(1, 3)
if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1
result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"
print (result)
我想循环这个直到a高于190并且b高于140且高于110但是它在第一次运行后每次都停止。
有人可以帮助我吗?
答案 0 :(得分:4)
你可以略微改变逻辑,然后使用一个无限循环,然后在符合条件时使用break
:
while True:
# do stuff
if a >= 190 and b >= 140 and c >=110:
break
如果符合任何条件,您的原始逻辑就会终止。例如,此循环退出是因为a
在第一次迭代后不再是True
:
a = True
b = True
while a and b:
a = False
此循环无限,因为b
始终为True
:
a = True
b = True
while a or b:
a = False
您可以使用or
代替and
进行初始while
循环,但我发现break
逻辑更加直观。
答案 1 :(得分:1)
您正在循环正文中重置a
,b
和c
。
试试这个:
>>> count = 0
>>> while a < 190 and b < 140 and c < 110 and count < 10: # <-- This condition here
... count += 1
... a = 0
... b = 0
... c = 0
... print(count, a, b, c)
...
(1, 0, 0, 0)
(2, 0, 0, 0)
(3, 0, 0, 0)
(4, 0, 0, 0)
(5, 0, 0, 0)
(6, 0, 0, 0)
(7, 0, 0, 0)
(8, 0, 0, 0)
(9, 0, 0, 0)
(10, 0, 0, 0)
>>>
答案 2 :(得分:0)
实际上你只是在展示&#34; a,b,c&#34;当while循环迭代并且你在每个循环中递增465次。这意味着如果你的while循环工作4次,它将随机增加a,b,c 465 * 4次。并且你的价值对于这种增量来说太小了。作为一种解决方案,你可以减少465号码,如果你使它达到250,你会看到它会工作直到c达到110以上并完成迭代。
for i in range(1, 250):
v = random.randint(1, 3)
250 c达到114并完成迭代。这是因为250 / 3~ = 83。当数字随机分配时,c是最常见的限制因素。我想你想要这样的东西;
import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
v = random.randint(1, 3)
if v == 1:
a = a + 1
elif v == 2:
b = b + 1
else:
c = c + 1
result = ""
result += "a: " + str(a) + "\n"
result += "b: " + str(b) + "\n"
result += "c: " + str(c) + "\n"
print (result)
它会逐一显示每个增量,当某些需求在while循环中遇到时它会停止。