2016-01-30 50 views
0
運行簡單的輸入任務時

我試圖運行的Python代碼,這些簡單的線條:錯誤在Python

myName = input("What is your name?") 
print (myName) 

if (myName == 'Omar'): 
    print ("Omar is great!") 
else: 
    print ("You are ok") 

它運行好,如果我用怠速運轉,但一旦我把它放在一個文本文件以「.py」爲擴展我得到以下輸出和錯誤:

What is your name?omar 
Traceback (most recent call last): 
    File "hello.py", line 2, in <module> 
    myName = input("What is your name?") 
    File "<string>", line 1, in <module> 
NameError: name 'omar' is not defined 

我不知道錯誤指出‘奧馬爾’需要加以界定,即使‘奧馬爾’是一個簡單的字符串輸入。

幫助將不勝感激,謝謝。

回答

1

使用raw_input

myName = raw_input("What is your name?") 

input在python 3用於及其蟒2當量是raw_input。 python中的input 2致電raw_input,致電eval,這是您的錯誤的來源。假定你使用IDLE和命令提示符的不同版本而沒有意識到它。

如果你需要一個跨Python的解決方案,你可能想看看這個問題How do I use raw_input in Python 3

0

看起來你的IDLE配置爲使用python 3,它對input()函數有良好的行爲,但是你從命令行運行python 2。在python 2中,input不符合你的期望,而應該使用raw_input。 (raw_input作爲字符串返回輸入,這是你想要的)