python input()与raw_input()
2016-03-31 15:06
471 查看
python中input()与raw_input()都可以用来接收用户的输入,但是两者还是有区别的。
我们来看下他们不同的地方:
可见raw_put()都会转化为原始输入的字符串形式,而input()会要求用户输入合法的python表达式并且会自动的计算,如果想输入’a’却没有加引号就会被理解为未定义的变量就会报错。
那么python中提供了eval这个内建函数,可以把raw_input()的效果转换为input():
eval(raw_input()),我们看下效果:
但是可惜的是python3.0中raw_input被重命名为了input,也就是说:
我们想实现python2中的raw_input()直接打input()就ok;
我们想实现python2中的input()就要打eval(input())才行。
我们来看下他们不同的地方:
>>> input() 1 1 >>> raw_input() 1 '1'
>>> input() 'a' 'a' >>> raw_input() 'a' "'a'"
>>> input() a Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'a' is not defined >>> raw_input() a 'a'
>>> input() 1+1 2 >>> raw_input() 1+1 '1+1'
>>> input() 'a'+'a' 'aa' >>> raw_input() 'a'+'a' "'a'+'a'"
>>> input() 'a'+1 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> TypeError: cannot concatenate 'str' and 'int' objects >>> raw_input() 'a'+1 "'a'+1"
可见raw_put()都会转化为原始输入的字符串形式,而input()会要求用户输入合法的python表达式并且会自动的计算,如果想输入’a’却没有加引号就会被理解为未定义的变量就会报错。
那么python中提供了eval这个内建函数,可以把raw_input()的效果转换为input():
eval(raw_input()),我们看下效果:
>>> eval(raw_input()) 1+1 2
但是可惜的是python3.0中raw_input被重命名为了input,也就是说:
我们想实现python2中的raw_input()直接打input()就ok;
我们想实现python2中的input()就要打eval(input())才行。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法