2016-09-23 80 views
0

干杯,我的问题是,我不知道如何做一段时间的多个条件。我真的,为什么这不会工作,不明白这一点:蟒蛇随机,而多个条件

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) 

我想这个循环直到高于上述高于110 140和c 190和B,但在第一次运行后,每次停止。

有人可以帮我吗?

回答

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逻辑更直观。

+0

我希望我每次都用0开始算法,所以总计不可能超过465。那就是我为什么这样做的原因。顺便说一句,这个答案做到了。你能告诉我为什么while-condition不起作用吗? –

+0

@PatrickMlr如果满足这些条件中的任何一个,你的初始'while'循环将会退出。例如,如果'a = 191',那么循环将终止 –

+0

因此,在Python或?真奇怪。 –

1

您正在重置循环体中的a,bc。 试试这个:

>>> 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) 
>>> 
0

其实你只显示“A,B,C” while循环迭代时,你在每个循环增加465倍。这意味着如果你的while循环工作4次,它会随机增加a,b,c,465 * 4次。而你的价值对于这种增量来说太小了。作为一种解决方案,如果您将它设置为250,则可以减少465个数字,您会看到它将工作到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循环中满足时它会停止。