Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to end while loop Python

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)]:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading