zoukankan      html  css  js  c++  java
  • 10:Python2与Python3比较

    1、print 函数

      1. print语句没有了,取而代之的是print()函数。 Python 2.6与Python 2.7部分地支持这种形式的print语法。

    2、Unicode

      1.  在python3中字符串默认是unicode所以不需要decode(),直接encode成想要转换的编码如gb2312

      2.  在python2中默认是ASCII编码,必须先转换成Unicode,Unicode 可以作为各种编码的转换的中转站 

    3、除法运算

      1. 在python 2.x中/除法相除的结果是一个整数,把小数部分完全忽略掉,浮点数除法会保留小数点的部分得到一个浮点数的结果。
      2. 在python 3.x中/除法不再这么做了,对于整数之间的相除,结果也会是浮点数。

    #1、python2
    >>> 1 / 2
    0
    >>> 1.0 / 2.0
    0.5
    
    #2、python3
    >>> 1/2
    0.5

    4、异常

      1. 在 Python 3 中处理异常也轻微的改变了,在 Python 3 中我们现在使用 as 作为关键词。

    #1、python2
    try:
        x = input("Enter the first number:")
        y = input("Enter the second number:")
        print x/y
    except (ZeroDivisionError, TypeError, NameError), e:
        print e
    #2、python3
    try:
        x = input("Enter the first number:")
        y = input("Enter the second number:")
        print(x/y)
    except (ZeroDivisionError, TypeError, NameError) as e:
        print(e)

    5、range与xrange

      1、在Python2中range生成的是一个列表,xrange生成的是一个生成器

      2、在Python3中废弃了xrange语法,只保留了range切效果和Python2中range类似

    6、不等运算符

      1. Python 2.x中不等于有两种写法 != 和 <>

      2. Python 3.x中去掉了<>, 只有!=一种写法,还好,我从来没有使用<>的习惯

    7、raw_input与input

      1. Python2中input得到的是int类型,raw_input得到的是str类型

      2. python3中废弃了raw_input语法,只有input的到的都是str类型

        原: raw_input( "提示信息" )

        改为: input( "提示信息" )

  • 相关阅读:
    sublime开启vim模式
    git命令行界面
    搬进Github
    【POJ 2886】Who Gets the Most Candies?
    【UVA 1451】Average
    【CodeForces 625A】Guest From the Past
    【ZOJ 3480】Duck Typing
    【POJ 3320】Jessica's Reading Problemc(尺取法)
    【HDU 1445】Ride to School
    【HDU 5578】Friendship of Frog
  • 原文地址:https://www.cnblogs.com/xiaonq/p/8706111.html
Copyright © 2011-2022 走看看