-1

I have the following code that should end when my number is no longer a certain tuple, such as (1,0) or (2,0). But when I run my code it runs infinitely or not at all cant figure out the problem.

import random

START = (random.randrange(0, 4), random.randrange(0, 4))

print(START)

while START==(1, 0) or (2, 0) or (1, 1) or (3, 2):

    START = (random.randrange(0, 4), random.randrange(0, 4))

else:

    print(START)
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53

3 Answers3

2

This is a common error, evaluating an argument followed by OR and different values will always evaluate to true. You can read a more in-depth answer here.

A good solution to avoid having to write multiple comparisons is to use the operator in. Replace:

while START==(1, 0) or (2, 0) or (1, 1) or (3, 2):

With

while START in [(1,0),(2,0),(1,1),(3,2)]:
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
1

try

while START==(1, 0) or START==(2, 0) or START==(1, 1) or START==(3, 2):

or

while START in [(1, 0), (2, 0), (1, 1), (3,2)]:

the else shouldn't be needed.

njp
  • 620
  • 1
  • 3
  • 16
0

Your while condition is incorrect causing it to be in a infinite loop. Either try doing while START==(1, 0) or START==(2, 0) or START==(1, 1) or START==(3, 2): or put the tuples into a list and just do START in list.

Stoobish
  • 1,202
  • 4
  • 23