繁体   English   中英

更高/更低的游戏:ValueError

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM