1. 程式人生 > >Python2中input出現的name “xxx” is not defined問題原因及解決辦法

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)