python中input()与raw_input()的区别

本文通过实例对比了Python中input()和raw_input()函数的区别。input()会尝试将输入作为Python表达式评估,而raw_input()则直接返回字符串形式的输入。文章强调了使用input()时需要注意的数据类型问题。
先看一段操作:
[13:51 t /tmp]$ python
Python 2.7.11 (default, Mar 31 2016, 20:46:51)
[GCC 5.3.1 20151207 (Red Hat 5.3.1-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> name=input("Your name:")
Your name:talen    #使用input()输入内容不加引号
Traceback (most recent call last):
  File "", line 1, in
  File "", line 1, in
NameError: name 'talen' is not defined
>>> name=input("Your name:")
Your name:"talen"    #使用input()输入内容添加引号
>>> print name
talen
>>> name=raw_input("Your name:")
Your name:talen        #使用raw_input()输入内容不加引号
>>> print name
talen
>>>
从上面的例子可以看出,如果想输入字符串,input()的输入内容必须使用''号,否则会被认为是变量名。
>>> num=input("Your num:")
Your num:897
>>> type(num)

>>> num2=raw_input("Your num:")
Your num:897
>>> type(num2)

>>>
从这个操作来看,input()接受了输入的数据类型,raw_input()把输入当作字符串来看。所以input()输入必须进行数据类型的转换才能正确表达第一个例子中的输入。
input ( [ prompt ] )

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值