python 2 版本中的input() 和 raw_input() 函数的比较

对于,类似的函数,我是不太喜欢的;

每次用的时候,因为,记性不好,每次都不敢肯定的去用函数,还需要去查询;

python 中 input() 跟 raw_input() 函数就是;

下面来拿书中的例子来说明下,这两个函数的用法;

>>> input("enter a word:")
enter a word:nihao
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'nihao' is not defined

 

当你输入 nihao 的时候,会发现他会报错,输入的name 不能被定义;

如果输入“nihao”,这时,就没有问题,也就是说 input 它会做一下校验,

而 raw_input() ,它不会做校验,你输入的内容,它会直接当做字符串;

>>> input("enter a number:")
enter a number:3
3
>>> raw_input("enter a number:")
enter a number:3
'3'

>>> input("enter a word:")
enter a word:nihao
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'nihao' is not defined


>>> raw_input("enter a word:")
enter a word:nihao
'nihao'

>>> input("Enert a word:")
Enert a word:"nihao"
'nihao'

上面的就能看出问题所在;

所以,如果使用的是python 2 的版本开发,就需要你考虑一下,你提取的都是字符还是有数字;

 

而在python 3中 raw_input() 函数已经被取消,只有函数input();

 

posted on 2017-03-06 17:46  aiyq195  阅读(193)  评论(0编辑  收藏  举报

导航