Home > Blockchain >  How to use logical operators in a while loop?
How to use logical operators in a while loop?

Time:04-30

I am trying to make a code that rolls 3 dice until they are the same. I have a while statement so it keeps on rolling until I have rolled 3 dice that are the same.

count = 1
import random 
dice_1 = random.randint(1, 6) 
dice_2 = random.randint(1, 6)
dice_3 = random.randint(1, 6)
print("die 1 = "   str(dice_1)   " die 2 = "   str(dice_2)   " dice 3 = "   str(dice_3))
while dice_1 != (dice_2 and != dice_3): 
    dice_1 = random.randint(1, 6)
    dice_2 = random.randint(1, 6)
    dice_3 = random.randint(1, 6)
    print("die 1 = "   str(dice_1)   " die 2 = "   str(dice_2)   " dice 3 = "   str(dice_3))
    count = count   1 
print(" ")     
print("It took "   str(count)   " tries to get a double")

In my while statement, I want it so when dice 1 does not equal dice 2 and dice 3, keep running. It is giving me invalid syntax error.

I have also tried,

while dice_1 != (dice_2 and dice_3): 

But when I do that, the loop finishes once dice_1 and dice_3 are the same.

CodePudding user response:

You should test using:

while dice_1 != dice_2 and dice_1 != dice_3 and dice_2 != dice_3:

Or you could do something more easily extendable for more dice:

while len(set([dice_1, dice_2, dice_3])) != 1:

CodePudding user response:

SUGGESTION: roll the dice inside the loop, then "break" if all three are equal:

count = 1
import random 
print("die 1 = "   str(dice_1)   " die 2 = "   str(dice_2)   " dice 3 = "   str(dice_3))
while True: 
    dice_1 = random.randint(1, 6)
    dice_2 = random.randint(1, 6)
    dice_3 = random.randint(1, 6)
    if (dice_1 == dice_2 and dice_2 == dice_3) :
        break;
    print("die 1 = "   str(dice_1)   " die 2 = "   str(dice_2)   " dice 3 = "   str(dice_3))
    count = count   1 
print(" ")     
print("It took "   str(count)   " tries to get a double")

CodePudding user response:

If you are using latest python(>=3.9) then you can use this code snippet

while ((die1:=random.randint(1,6)) and (die2:=random.randint(1,6)) and (die3:=random.randint(1,6))):
    if (die1 == die2) and (die2==die3):
        break
    print(die1, die2, die3)
print(die1, die2, die3)
  • Related