【问题标题】:I want my code to only allow inputs from 1-10我希望我的代码只允许输入 1-10
【发布时间】:2019-02-02 17:13:42
【问题描述】:

我刚刚开始编码并将 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()

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

【问题讨论】:

    标签: python-3.7


    【解决方案1】:

    你可以改进你的 if 语句

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

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      相关资源
      最近更新 更多