
关于Python 2.7版本与最新的3.0版本 有关input()函数返回值问题;
3.0的版本返回值返回的都是str型,所以:Python3.3.0(v3.3.0:bd8afb90ebf2,Sep292012,10:57:17)[MSCv.160064...
3.0的版本返回值返回的都是str型,所以:
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> x=input ()
21
>>> y=input ()
22
>>> print (x*y)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print (x*y)
TypeError: can't multiply sequence by non-int of type 'str'
>>>
应该使用强制转换:
>>>
>>> x=int (input ())
21
>>> y=int (input())
22
>>> print (x*y)
462
但是在2.7版本就不需要强转,我想知道2.7版本时是自动转还是什么原理:
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:22:14) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> x=input ()
21
>>> y=input ()
22
>>> print x*y
462
>>> 原理是什么? 展开
Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> x=input ()
21
>>> y=input ()
22
>>> print (x*y)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
print (x*y)
TypeError: can't multiply sequence by non-int of type 'str'
>>>
应该使用强制转换:
>>>
>>> x=int (input ())
21
>>> y=int (input())
22
>>> print (x*y)
462
但是在2.7版本就不需要强转,我想知道2.7版本时是自动转还是什么原理:
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:22:14) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> x=input ()
21
>>> y=input ()
22
>>> print x*y
462
>>> 原理是什么? 展开
2个回答
展开全部
2.7的版本在使用input()函数的时候,会调用eval()这个函数。所以不需要转换。
展开全部
3.0以后的版本跟2.7的版本在语法上有一些差别的。
3.0中的input(),其实对应的是2.7中的raw_input(),功能是读取用户输入的字符串,也就是说你在3.0中用imput获取的x、y其实是"21"、"22"。
而2.7中的input(),的功能是读取用户输入的数字,可以试试在2.7中
>>> x=input ()
abc
这样是会报错的,因为abc不是数字。
可以参考以下代码来理解:
#==========pyhon2.x中================
>>> a=input()
12
>>> a
12
>>> b=raw_input()
12
>>> b
'12'
#==========pyhon3.x中================
>>> b=input()
12
>>> b
'12'
3.0中的input(),其实对应的是2.7中的raw_input(),功能是读取用户输入的字符串,也就是说你在3.0中用imput获取的x、y其实是"21"、"22"。
而2.7中的input(),的功能是读取用户输入的数字,可以试试在2.7中
>>> x=input ()
abc
这样是会报错的,因为abc不是数字。
可以参考以下代码来理解:
#==========pyhon2.x中================
>>> a=input()
12
>>> a
12
>>> b=raw_input()
12
>>> b
'12'
#==========pyhon3.x中================
>>> b=input()
12
>>> b
'12'
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询