Python:输入接受整数但在字符串上崩溃

时间:2015-10-03 18:41:25

标签: python

对于我作业中的练习题,我正在制作一个猜谜游戏,首先要求一个数字。我正在尝试实现一种在给定字符串时打印“无效输入”的方法,但是我收到错误消息。这是我的代码:

def get_input():
    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''
    guess=int(input("give me 1,2,3"))
    while True:
        if guess==1 or guess==2 or guess==3:
            return guess
        else:
            print "Invalid input!"

        guess=int(input("give me 1,2,3"))

当我输入

等字符串时,我收到此消息
hello/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/bob/PycharmProjects/untitled/warmup/__init__.py

给我1,2,3hello

Traceback (most recent call last):
  File "/Users/bob/PycharmProjects/untitled/warmup/__init__.py", line 51, in <module>
    get_input()
  File "/Users/bob/PycharmProjects/untitled/warmup/__init__.py", line 43, in get_input
    guess=int(input("give me 1,2,3"))
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

Process finished with exit code 1

2 个答案:

答案 0 :(得分:5)

你需要对python2使用raw_input,输入尝试评估字符串,以便查找名为name的变量和错误,因为在任何地方都没有定义名为name的变量。你永远不应该在python2中使用input,它等同于eval(raw_input()),它具有明显的安全风险。

所以要更清楚地拼写出来,不要使用输入从python2中的用户那里获取输入,使用raw_input()并在您的情况下使用raw_input try/except抓住ValueError

def get_input():
    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''

    while True:
        try:
            guess = int(raw_input("give me 1,2,3"))
            if guess in (1, 2, 3):
                return guess
        except ValueError:
            pass
        print("Invalid input!")

你只是在为1,2或3而掏钱,这意味着你也可以在确认之后进行投射:

def get_input():
    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''

    while True:
        guess = raw_input("give me 1,2,3")
        if guess in ("1", "2", "3"):
            return int(guess)
        print("Invalid input!")

答案 1 :(得分:1)

您应该在转换为int之前验证输入类型:

guess = raw_input("give me 1,2,3")

while True:
   if guess == '1' or guess == '2' or guess == '3':
      return int(guess)
   else:
      print "Invalid input!"

   guess = raw_input("give me 1,2,3")