2014-01-21 63 views
1

我是一个Python newbie.I正在逐渐熟悉环和一本书蟒蛇输入()无法正常运行

while True: 
     s = input('Enter something : ') 
     if s == 'quit': 
       break 
     print('Length of the string is', len(s)) 
print('Done') 

然而,输出如下

Enter something : ljsdf 
Traceback (most recent call last): 
    File "trial_2.py", line 2, in <module> 
    s = input('Enter something : ') 
    File "<string>", line 1, in <module> 
NameError: name 'ljsdf' is not defined 
+0

为它的价值:这基本上是http://stackoverflow.com/q/11295325/的副本748858虽然你可能无法找到它,如果你不知道在哪里看... – mgilson

回答

4

您必须改用raw_input()(Python 2.x),因为input()相当于eval(raw_input()),因此它将输入解析并计算为有效的Python表达式。

while True: 
     s = raw_input('Enter something : ') 
     if s == 'quit': 
       break 
     print('Length of the string is', len(s)) 
print('Done') 

注:

input()不捕获用户错误(例如,如果用户输入一些无效Python表达式)。 raw_input()可以做到这一点,因为它将输入转换为stringFor futher information, read Python docs

+0

我觉得你的笔记有点向后。 'raw_input()'不会将输入*转换为*字符串,而不是*尝试将所述字符串评估为代码。 – mhlester

+0

我刚刚引用了[Python文档](http://docs.python.org/2/library/functions.html) – Christian

+0

非常好! – mhlester

2

试过了这个例子你想在raw_input() python2

while True: 
    s = raw_input('Enter something : ') 
    if s == 'quit': 
      break 
    print 'Length of the string is', len(s) 
print 'Done' 

input()试图评估(dangero usly!)你给它

2

您的代码将在Python 3.x的做工精细

但是,如果你使用Python 2,你会使用的raw_input()必须输入字符串

while True: 
    s = raw_input('Enter something : ') 
    if s == 'quit': 
     break 
    print('Length of the string is', len(s)) 
print('Done') 
1

在Python 2.x的input()设计要根据用户的输入返回数字,int或float,还可以输入变量名称。

你需要使用:

raw_input('Enter something: ') 

的错误造成的,因为Python的认为“ljsdf”是一个变量的名字,这就是为什么它会引发此异常:

NameError: name 'ljsdf' is not defined

因为“ljsdf”未被定义为变量。 :d

raw_input()使用更安全,然后输入转换为任何其他类型后:d