2014-01-21 58 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