下面的代码在Python2中的输出是什么?解释你的答案

 python2

def div1(x,y):
    print "%s/%s = %s" % (x, y, x/y)

def div2(x,y):
    print "%s//%s = %s" % (x, y, x//y)

div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)
div2(5.,2)
div2(5,2.)

另外,在Python3中上面的代码的输出有何不同(假设代码中的print语句都转化成了Python3中的语法结构)

在Python2中,代码的输出是:

5/2 = 2
5.0/2 = 2.5                                                 
5//2 = 2                                                    
5.0//2.0 = 2.0                                              
5.0//2 = 2.0                                                
5//2.0 = 2.0                                                
[Program finished]

默认情况下,如果两个操作数都是整数,Python2默认执行整数运算。所以,5/2 结果是2,而5./2结果是2.5

注意你可以通过下面的import语句来覆盖Python2中的这一行为

from __future__ import division

还要注意“双斜杠”(//)操作符将会一直执行整除,忽略操作数的类型。这就是为什么5.0//2.0即使在Python2中结果也是2.0

但是在Python3并没有这一行为。两个操作数都是整数时,也不执行整数运算。在Python3中,

def div1(x,y):
    print("{}/{}= {}".format(x, y, x/y))

def div2(x,y):
    print("{}//{} = {}".format(x, y, x//y))

div1(5,2)
div1(5.,2)
div2(5,2)
div2(5.,2.)

输出如下:

5/2= 2.5
5.0/2= 2.5                                                  
5//2 = 2                                                    
5.0//2.0 = 2.0                                             
[Program finished]
原文地址:https://www.cnblogs.com/sea-stream/p/11188335.html