1、整数相除: python2结果为整数, 舍弃余数部分;python3结果为浮点数
print(3 / 2)
# python2: 1
# python3: 1.5
print(type(3 / 2))
#python2: <type 'int'>
#python3: <class 'float'>
2、python3废弃long类型,统一使用int类型
a=111111111111
print(type(a))
#python2: <type 'long'>
#python3: <class 'int'>
3、python3 round函数返回int类型,而python2 返回的是float类型
print(type(round(2.1)))
type 'float'> python2: <
'int'> python3: <class
4、python3 废弃了print语句,统一使用print函数
#python2 正常,python3编译错误
print "hello"
#python3 统一使用print函数
print("hello")
5、python3 废弃exec语句,统一使用exec函数
#python2 正常,python3编译错误
exec "print('hello')"
#python3 统一使用exec函数
exec("print('hello')")
6、python3 废弃不等于操作符‘<>’,统一使用‘!=’
a = 1
if a <> 2: #python2 正常,python3编译错误
print "no"
if a != 3: #python2和python3 都支持
print "ok"
7、python3 废弃raw_input函数,统一使用input函数
#python3 已废弃row_input函数
data=raw_input('input a number=>')
print(data)
#python2、python3 都支持input函数
data=input('input a number=>')
print(data)
8、python3 dict废弃has_key方法
mydic={'a':1}
print(mydic.has_key('a'))
#python2: True
#python3: AttributeError: 'dict' object has no attribute 'has_key'
9、python3 废弃apply函数
def sum(a,b):
return a+b
#python2正常,python3编译错误
result=apply(sum,(1,2))
print(result)
#python2: 3
10、python3 废弃xrange函数,统一使用range函数
# python2正常,python3 编译错误
for i in xrange(1, 10, 2):
print(i)
# python3 统一使用range函数
for i in range(1, 10, 2):
print(i)
11、python2 比较运算符可以作用在不同类型数据上,而python3只能作用在相同类型数据上
print(11<'hello')
python2: True
'<' not supported between instances of 'int' and 'str' python3: TypeError:
12、异常写法不同
#python2 写法
try:
a = 0
if a == 0:
raise ValueError, "a can't be zero"
except Exception, ex:
print(ex)
#python3 写法
try:
a = 0
if a == 0:
raise ValueError("a can't be zero")
except Exception as ex:
print(ex)
–end
转载请注明:XAMPP中文组官网 » Python3与Python2 区别有哪些?