输入中字符串的Python NameError

时间:2018-05-04 15:10:07

标签: python python-2.7

我在尝试强制执行python代码时遇到问题,以避免在输入中提供特定范围之外的数字。

我创建了一个要监控的进程列表,subselect函数用于检查输入的有效性。接受的值应来自1 to 9

我的设计适用于数字,但如果错误地给出了另一种类型,我会得到NameErr

def subselect():
    while True:
        choise = input("Please select a Subsystem to monitor: ")
        print(type(choise))
        print(choise)
        if int(choise) <= 0 or choise >= 10:
           print("Selection invalid")
        else:
           return choise


if __name__== "__main__":
    subsystem = ["","a","b","c","d","e","f","g","h"]
    while True:
        print("1  - a")
        print("2  - b")
        print("3  - c")
        print("4  - d")
        print("5  - e")
        print("6  - f")
        print("7  - g")
        print("8  - h")
        print("9  - i")
    select = subselect()

执行脚本如果提供的输入不是数字,我会得到NameError。

1  - a
2  - b
3  - c
4  - d
5  - e
6  - f
7  - g
8  - h
9  - i
Please select a Subsystem to monitor: 20
<type 'int'>
20
Selection invalid
Please select a Subsystem to monitor: fff

Traceback (most recent call last):
  File "./MyScript.py", line 102, in <module>
    select = subselect()
  File "./MyScript.py", line 72, in subselect
    choise = input("Please select a Subsystem to monitor: ")
  File "<string>", line 1, in <module>
**NameError: name 'fff' is not defined**

我也尝试使用int但结果相同 choise = int(输入(“请选择要监控的子系统:”))

1 个答案:

答案 0 :(得分:0)

如果您使用的是python 2,则需要使用raw_input,如下所示:

choise = raw_input("Please select a Subsystem to monitor: ")

因为在python2.x中,input返回原始代码而不是字符串。但是在python3.x中,你需要这样的东西来获取原始代码:

exec('a='+input('enter some raw code'))

或者如果你只想要一个变量:

a=eval(input('enter a variable (like this: var) that has been previously assigned, or like this: 'some text', 5, [1, 2, 3]'))