Python2中input出现的name “xxx” is not defined问题原因及解决办法

来源:互联网 发布:淘宝网的案例分析 编辑:程序博客网 时间:2024/05/17 08:16

# 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:helloTraceback (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:Pythonstr_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)


阅读全文
0 0
原创粉丝点击