input 和 raw_input 的比较

input 和 raw_input 的比较

python2.7
这里主要以两个例子来说明两者不同。
例1
在一个脚本文件hello1.py中输入下面语句:

name=raw_input("what is your name?:")
print('hello,'+name+'!')

运行该程序,输入:wang

>>> =======================RESTART=========================
>>>
what is your name?:wang
hello,wang!
>>>

在一个脚本文件hello2.py中输入下面语句:

name=input("what is your name?:")
print('hello,'+name+'!')

运行该程序,输入:wang

>>> =======================RESTART=========================
>>>
what is your name?:wang

Traceback (most recent call last):
  File "E:\python\python\hello2.py", line 2, in <module>
    name=input("what is your name?:")
  File "<string>", line 1, in <module>
NameError: name 'wang' is not defined  
>>>

运行该程序,输入:”wang”

>>> =======================RESTART=========================
>>>
what is your name?:wang
hello,wang!
>>>

虽然这种输入方式可以得到正确结果,但是,让用户输入带引号的名字太麻烦。
再举一个例子。

例2:

>>> input ('enter a number:')
enter a number:43
43
>>> raw_input('enter anumber:')
enter anumber:43
'43'
>>>

由上面两个例子,可以看出:input的用户输入必须是python合法的表达式(上面例子中输入wang结果出错,而出入合法的 字符串’wang’结果正确),raw_input会把用户输入的数据放入字符串中(上面例子中输入43,而实际4是按照字符串‘43’的格式存储)。
应尽可能的使用raw_input 函数。

python3.6.5中没有raw_input()函数只有input()函数
这里写图片描述

python3.6.5版本中input()函数的输入都以str形式存储。

>>> x=input('number:')

number:3
>>> type(x)

<class 'str'>
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值