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:
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))