gpt4 book ai didi

python - 高/低游戏 : ValueError

转载 作者:行者123 更新时间:2023-12-02 16:00:10 26 4
gpt4 key购买 nike

对于我的脚本类(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)

最佳答案

您必须检查 lower 是否大于 upper。也可以使用min/max取最低值和最高值:

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

关于python - 高/低游戏 : ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70889172/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com