zoukankan      html  css  js  c++  java
  • 下面的代码在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]
  • 相关阅读:
    fabric-byfn.sh名利解析
    Hyperledger Fabric--byfn.sh 命令分析
    ubuntu修改网络地址
    docker常用命令
    添加daocloud加速器-18.04.2-Ubuntu
    CA/RA简介
    Redhat防火墙
    Linux上Oracle 11g启动与关闭
    redhat网络配置文件详解
    uva1349Optimal Bus Route Design
  • 原文地址:https://www.cnblogs.com/sea-stream/p/11188335.html
Copyright © 2011-2022 走看看