您的位置:首页 > 其它

input()和raw_input()区别

2015-07-01 17:06 567 查看
input的源码:

def input(prompt):

    return eval(raw_input(prompt))

看个例子:

>>> user = raw_input('enter your name \n')

enter your name

liubei

>>> user

'liubei'

>>> user = input('enter your name \n')

enter your name

zhaoyun

提示error:

Traceback (most recent call last):

  File "<pyshell#12>", line 1, in <module>

    user = input('enter your name \n')

  File "<string>", line 1, in <module>

NameError: name 'zhaoyun' is not defined

raw_input()可以把把任何的用户输入转换为字符串存储。

input()则不会自动转换。必须输入符合要求的字符串。因为input总是假定用户输入的是合法的pytho表达式。

>>> user = input('enter your name \n')

enter your name

'lvbu' #以字符串作为输入

>>> user

'lvbu'

当输入为字符串表达式时:input会计算字符串中的数字表达式。    raw_iput不会,直接输入字符串表达式。如下:

>>> count = input()

57+3

>>> count

60

>>> count = raw_input()

57+3

>>> count

'57+3'

>>>

当输入为纯数字时,input返回的是数值类型,如int,float.   raw_input返回的是字符串类型,string类型。如下:

>>> user = input('enter the number')

enter the number123456789

>>> user

123456789

>>> user = raw_input('enter the number')

enter the number123456789

>>> user

'123456789'

>>>

提示:除法对有input有特殊要求,否则应该尽可能使用raw_input函数。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: