我希望我的代码只允许输入 1-10

I want my code to only allow inputs from 1-10

我刚刚开始编码,python 是我的第一语言。我决定做这个猜数字的小项目,我已经走到这一步了。它工作得很好,但我希望用户只输入 1-10 之间的数字,如果超过该数字或给出不在该范围内的其他输入。我想打印一段文字。

我一直在搜索 python 文档,但没有找到任何东西,我很确定它在条件下非常简单,但我无法弄清楚它是什么。

此外,如果您发现可以改进此代码的任何方式,请告诉我,我很想知道它

def game():
    mysteryNumber = random.randint(1,10)
    print("I just guessed a number.")
    inputByUser = input("Now choose a number from 1 to 10 : ")
    chosenNumber = int(inputByUser)

    if mysteryNumber == chosenNumber:
        print("You guessed it right.")
    elif mysteryNumber > chosenNumber:
        print("Too low. Try again buddy.")
    elif mysteryNumber < chosenNumber:
        print("Too high. Try again buddy.")
    else:
        print("The number you chose ' {} ' is not a valid number.".format(chosenNumber))

Here is a picture of the full code

编辑:没关系我自己想出来我在第一个 if 语句后添加了这行代码

elif chosenNumber > 10:
    print("The number you chose ' {} ' is not a valid number.".format(chosenNumber))
    game()

这不是一个完美的解决方案,因为它没有在范围内进行检查,但我会在以后了解更多相关信息

您可以改进您的 if 语句

elif (chosenNumber > 10) or (chosenNumber < 1):
    print("The number you chose ' {} ' is not a valid number.".format(chosenNumber))
    game()