【问题标题】:Loops and comparing strings in homework assignment家庭作业中的循环和比较字符串
【发布时间】:2018-10-06 04:26:43
【问题描述】:

我的 Python 简介作业需要帮助。

任务是让计算机在 1 到 100 之间选择一个随机数,用户必须猜测该数字。如果您的猜测太高,那么您将被告知。如果您的猜测太低,那么您将被告知。它将继续重复,直到您猜出生成的正确数字为止。

我的问题是,如果输入是一个字符串,那么你会得到一个提示,说这不是一个可能的答案。我该如何解决这个问题?

附:如果不会太麻烦,我想获得有关如何修复我的代码的提示,而不是答案。

代码:

import random

#answer= a
a= random.randint(1,100)

#x= original variable of a
x= a

correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")

#guess= g

while not correct:

    g= input("Please enter a number between 1 and 100: ", )

    if g == "x":

       print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")

    elif int(g) < x:

        print("your guess was too low, try again.")

    elif int(g) > x:

        print("your guess was too high, try again.")

    else:

        print("Congratulations, you guessed the number!")

【问题讨论】:

    标签: python


    【解决方案1】:

    因此,如果您想清理输入以确保只输入数字,您可以使用isdigit() 方法进行检查。例如:

    g=input("blah blah blah input here: ")
    if g.isdigit():
        # now you can do your too high too low conditionals
    else:
      print("Your input was not a number!")
    

    您可以通过this StackOverflow thread了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多