samedi 18 juillet 2020

python while loop doesnt stop when meeting set condition [duplicate]

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)

im facing a problem here, i want the loop to stop when one of the conditions is achieved. the loop works when instead of 2 conditions i have 1, for example:

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

one of these above will loop until the coin is in the set state and will give me the number of tries, so this works.

but if i change to this:

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

it will loop endlessly because it probably is trying to achieve both conditions of coin 1 and coin 2 even though its set to "or" and not "and". it cant do that because there is no "coin 2 is down" for st1, st1 as in state 1 which is for coin1, not coin2.

if you need any more info ill do my best to provide.




Aucun commentaire:

Enregistrer un commentaire