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

mag*_*ber 3 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"))
Run Code Online (Sandbox Code Playgroud)

当我输入诸如的字符串时,我收到此消息

hello/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/bob/PycharmProjects/untitled/warmup/__init__.py
Run Code Online (Sandbox Code Playgroud)

给我吗 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
Run Code Online (Sandbox Code Playgroud)

Pad*_*ham 5

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

所以要更清楚地拼写出来,不要使用输入来从python2中的用户那里获取输入raw_input(),在你的情况下使用和raw_input使用一个try/except捕获a 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!")
Run Code Online (Sandbox Code Playgroud)

您只需要为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!")
Run Code Online (Sandbox Code Playgroud)