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

Higher/Lower Game: ValueError

For my scripting class, we have to make a higher/lower game. This is my code so far:

import random

seedVal = int(input("What seed should be used? "))
random.seed(seedVal)
lower = int(input("What is the lower bound? "))
upper = int(input("What is the upper bound? "))
number = random.randint(lower, upper)

while (True):
    guess = int(input("What is your guess? "))
    if(number < lower or number > upper):
        print("The number should be between the upper bound and the lower bound")
    elif(guess == number):
        print("You got it!")
        break
    elif(guess < number):
        print("Nope, too low.")
    else:
        print("Nope, too high.")

It has worked for 3/4 functionality tests however it fails when I input:
2
5
1
1
5
1
2
3
4
5

The error it gives me is:

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

Traceback (most recent call last):
  File "HigherLowerGame.py", line 7, in <module>
    number = random.randint(lower, upper)
  File "/usr/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python3.8/random.py", line 226, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (5, 2, -3)

>Solution :

You have to check if lower is greater than upper. You can also use min/max to take the lowest and highest value:

lower = int(input("What is the lower bound? "))
upper = int(input("What is the upper bound? "))
number = random.randint(min(lower, upper), max(lower, upper))
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