【问题标题】:Python allowing word input [duplicate]Python允许输入单词[重复]
【发布时间】:2016-02-04 00:49:41
【问题描述】:

我无法让用户输入除整数以外的任何内容,因为这样做会导致程序崩溃并且无法打印出我想要的文本。

这是终端中的程序。

【问题讨论】:

  • 请复制粘贴实际代码。不要只是链接到图片 - 这很烦人而且没有必要。
  • 在 python 2 中使用 raw_input 而不是 input!

标签: python string terminal integer


【解决方案1】:

python 2.x 需要使用 raw_input()

guess = raw_input()

还有代码

elif: #Need help here!

在语法上无效 - 它需要一个条件子句。但是查看您的代码,您可能可以将“elif:”删除到“break”,因为它只是复制了它下面的内容。

【讨论】:

    【解决方案2】:

    你应该使用的第 6 行和第 20 行

    print 'No its '+str(ans)
    

    【讨论】:

      【解决方案3】:
      from random import randint
      import sys
      
      # Python version compatibility shim
      if sys.hexversion < 0x3000000:
          # Python 2.x
          inp = raw_input
          rng = xrange
      else:
          # Python 3.x
          inp = input
          rng = range
      
      TRIES = 10
      
      def main():
          print("Welcome to the Math Challenge!")
          correct = 0
          for m in rng(1, TRIES + 1):
              n = randint(1, 16)
              answer = m * n
              guess = inp("What is {} x {}? ".format(m, n))
              try:
                  guess = int(guess)
                  if guess == answer:
                      print("That's right")
                      correct += 1
                  else:
                      print("Sorry, it's actually {}".format(answer))
              except ValueError:
                  # guess is not an int value
                  guess = guess.strip().lower()
                  if guess == "skip":
                      print("Skipping...")
                      continue
                  elif guess == "stop":
                      print("Stopping...")
                      break
          print("You got {} correct out of {}!".format(correct, TRIES))
      
      if __name__ == "__main__":
          main()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 2018-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-07
        • 2013-01-17
        相关资源
        最近更新 更多