Python2中input出現的name “xxx” is not defined問題原因及解決辦法

# coding=UTF-8
'''
Created on 2017年10月22日

@author: Dyna
'''
str_1 = input("Enter a string:")
str_2 = input("Enter another string:")

print ("str_1 is:"+str_1+" str_2 is:"+str_2)
print "str_1 is {} ,str_2 is {}".format(str_1, str_2)
以上爲用來測試Python中的輸入函數input:但是出現了以下情況:

Enter a string:hello
Traceback (most recent call last):
  File "/Users/Dyna/Documents/workspace/TeachingPython/Test_IO_Format.py", line 7, in <module>
    str_1 = input("Enter a string:")
  File "/Users/Dyna/Downloads/Eclipse.app/Contents/Eclipse/plugins/org.python.pydev_4.5.5.201603221110/pysrc/pydev_sitecustomize/sitecustomize.py", line 141, in input
    return eval(raw_input(prompt))
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

我在輸入hello時,進行報錯,

NameError: name 'hello' is not defined。

上Python官網上查詢了一下文檔,原因定位如下:

Python 2.X中對於input函數來說,它所希望讀取到的是一個合法的Python表達式,即你在輸入字符串的時候必須要用""將其擴起來,我的Python版本爲2.7,因此出現這個問題,而在Python 3中,input默認接受的是str類型。

解決辦法:1、在控制檯進行輸入參數時,將其變爲一個合法的Python表達式,用""將其擴起來

        2、使用raw_input,因爲raw_input將所有的輸入看作字符串,並且返回一個字符串類型。

1、

Enter a string:"hello"
Enter another string:"Python"
str_1 is:hello str_2 is:Python
str_1 is hello ,str_2 is Python
2、

# coding=UTF-8
'''
Created on 2017年10月22日

@author: Dyna
'''
str_1 = raw_input("Enter a string:")
str_2 = raw_input("Enter another string:")

print ("str_1 is:"+str_1+" str_2 is:"+str_2)
print "str_1 is {} ,str_2 is {}".format(str_1, str_2)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章