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)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值