[英]Higher/Lower Game: ValueError
對於我的腳本 class,我們必須制作更高/更低的游戲。 到目前為止,這是我的代碼:
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.")
它適用於 3/4 功能測試,但是當我輸入時失敗:2 5 1 1 5 1 2 3 4 5
它給我的錯誤是:
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)
我對 python 幾乎一無所知,但是對於該輸入序列,聽起來您要求 randint 生成一個隨機數,其中下限為 4,上限為 1,這是不可能的。
您必須檢查lower
是否大於upper
:
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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.