input和raw_input的区别

首先明确一点,input()与raw_input()的区别只存在Python2.X环境下,因为在Python3中将Python2中的input()删除了,同时将raw_input()改名为input()。
如果你主要使用Py3,那么你只需关注在使用input()时所输入的数据最后都会输出成字符串格式,所以当你进行数字格式输入时要利用int()做好格式转换。

Py2.x环境下运行:

# 例1
>>> a = input("Please input your age: ")
Please input your age: 18
>>> a
18
# 例2
>>> a = input("Please input your name: ")
Please input your name: jason
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'virgin' is not defined

通过例1与例2做对比,我们可以发现在Py2环境下使用input()函数输入字符串的话,必须严格按照以引号方式输入字符串,如下所示:

# 例3
>>> a = input("Please input your name: ")
Please input your name: "jason"
>>> a.title()
Jason
#  例4
>>> a = raw_input("Please input your name: ")
Please input your name: jason
>>> a.title()
'Jason'
>>> a = raw_input("Please input your age: ")
Please input your favorite number: 18
>>> a
'18'

通过例4我们可以直观地看到,在Py2环境下raw_input()函数会将所有输入的数据一律都转换为字符串格式.

结论:
如果想要在Py2环境下使用input()函数输入字符串的话,必须严格按照以引号方式输入字符串.当然更便捷的方法,尽量多使用raw_input()而避免使用input().很显然Py3环境下并不存在这个问题,因为只有input()可供使用.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值