满足设置条件时,python while循环不会停止

时间:2020-07-18 17:06:01

标签: python loops random operators

import random

#declaring variables
tries = 0
st1 = str("nothing")
st2 = str("nothing")

print("starting")

#loop until one of the coins lands in the right position
while st2 or st1 != "coin2 is down":
  #count how many loops or "tries" it took to meet the set condition
  tries = tries + 1

  #add chances 
  rand = random.randint(0, 100)

  if rand < 50:
    st1 = str("coin1 is up")
  elif rand > 50:
    st1 = str("coin1 is down")
  else:
    st1 = str("coin1 is spinning")
  #st as in state of the coin. so the coin has 49.5% of being down, 49.5% of being up and 1% of being in the middle and spinning (i guess)

  #now i purposely chose different chance numers to create a second random variable 
  rand2 = random.randint(50, 150)

  if rand2 < 100:
    st2 = str("coin2 is up")
  elif rand2 > 100:
    st2 = str("coin2 is down")
  else:
    st2 = str("coin2 is spinning")
  #the odds are the same i think, its just the variables are different.

  #this will print the state of the 2nd coin to keep track of it
  print(st2)
  #this will print the tries
  print(tries)
我在这里面临一个问题,我希望当条件之一达到时循环就停止。该循环在我有2个条件而不是2个条件时起作用,例如:

while st1 != "coin1 is down": 
#or this
while st2 != "coin2 is spinning": 

以上其中一项将循环运行,直到硬币处于设定状态,并给出尝试次数,因此此方法有效。

但是如果我改成这个:

while st1 or st2 != "coin2 is down": 

它会无限循环,因为即使将其设置为“或”而不是“与”,它也可能试图同时满足硬币1和硬币2的条件。之所以不能这样做,是因为状态1中的st1和st1没有“ coin 2 down”,这是在状态1中,它是针对coin1而不是coin2的。

如果您需要更多信息,请尽我所能提供。

1 个答案:

答案 0 :(得分:0)

这来自while st2 or st1 != "coin2 is down":,您必须将其更改为while st2 != "coin2 is down" or st1 != "coin2 is down":OR运算符(逻辑门)需要具备条件。如果您正在做st2 or st1 != "coin2 is down",则要检查第一个变量st2是否为True。您还必须在!= "coin2 is down"

之前的第一个变量中添加or