raw_input和input的区别

来源:互联网 发布:中卫云计算2018,130 编辑:程序博客网 时间:2024/05/21 09:06

二者区别简单来说

input()函数支持用户输入数字或者表达式,不支持输入字符串.返回的是数字类型的数值. 
raw_input()函数捕获的是用户的原始输入,返回为字符串.如果需要用输入的数字计算,则需要使用int()函数转换一下.如果我们直接用输入的数值与某数想加,那么解释器就会报错。


原文地址:http://blog.csdn.net/dq_dm/article/details/45665069

这两个均是 python 的内置函数,通过读取控制台的输入与用户实现交互。但他们的功能不尽相同。下面对它们逐一介绍:

1、raw_input函数

语法:raw_input([prompt]) 
如果prompt不存在,也就是raw_input(),它会标准输出(没有后面的换行符)。然后这个函数从输入读取一行,把它转化为字符串(移除尾部的换行符),并输出它。在这里移除尾部的换行符,也就是说,你输入一行时,会回车换行,这个换行不会作为字符串中的字符输出。 
如果prompt存在,prompt经常是字符串(用来提示输入),用法和prompt不存在一样。 
当读取到文件的结束符时会抛出异常。 
总的来说,raw_input将所有输入作为字符串看待,不管用户输入什么类型的都会转变成字符串。
>>> x=raw_input()  # prompt不存在
abc
>>> x
'abc'
>>> 
>>> y=raw_input("please input:")
please input:abc
>>> y
'abc'
>>> 
>>> z=raw_input("please input:")
please input:34
>>> z
'34'
>>> 
>>> m=raw_input("please input:")
please input:[2,3,1,4]
>>> m
'[2,3,1,4]'
>>> 
>>> n=raw_input("please input:")
please input:3+2
>>> n
'3+2'
>>> 

2、input函数
语法:input([prompt]) 
等价于:eval(raw_input(prompt)) 
我们知道eval函数是将字符串str当成有效Python表达式来求值,并返回计算结果。 
input函数期望用户输入的是一个有效的表达式,也就是说,如果要输入字符串就必须要用引号括起来,否则它会引发一个 SyntaxError。它会根据输入内容的形式确定返回的形式。
>>> x=input()
"abc"
>>> x
'abc'
>>> 
>>> y=input("please input:")
please input:abc
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    y=input("please input:")
  File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
>>> 
>>> z=input("please input:")
please input:3
>>> z
3
>>> 
>>> m=input("please input:")
please input:3+2
>>> m
5
>>> 
除非对 input有特别需要,否则一般情况下我们都是推荐使用 raw_input来与用户交互,这样能避免程序中出现一些不必要的麻烦。此时只需对其转换一下而已。
>>> x=int(raw_input("please input:"))  # 获取输入的整数
please input:34
>>> x
34
>>> type(x)
<type 'int'>
>>> 
>>> y=float(raw_input("please input:"))  # 获取输入的浮点数
please input:34.2
>>> y
34.2
>>> type(y)
<type 'float'>
>>> 
0 0
原创粉丝点击