Loading

Python 2和3语法区别

环境

  • python2
Python 2.7.10 (default, Feb  7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
  • python3
Python 3.7.3 (default, Mar 27 2019, 09:23:32)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

print

  • python3中不再支持如下写法
    print 'aaa','bbb'
    
  • python2中print是语句,python3中是函数
    print('aaa','bbb') # 两者输出不同
    print('aaa') # 输出相同
    

请看代码

  • python3
    >>> print 'aaa', 'bbb'
      File "<stdin>", line 1
        print 'aaa', 'bbb'
                  ^
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print('aaa', 'bbb')?
    >>> print('aaa','bbb')
    aaa bbb
    >>> print('aaa')
    aaa
    
  • python2
    >>> print 'aaa', 'bbb'
    aaa bbb
    >>> print('aaa','bbb')
    ('aaa', 'bbb')
    >>> print('aaa')
    aaa
    
    

在py2中,print语句后面跟的是元组对象,所以会打印出('aaa','bbb')

而py3中print作为函数接收多个参数。

当然。Python 2.6实际已经支持新的print()语法, 导入下面的包就可以。

>>> from __future__ import print_function
>>> print('aaa','bbb')
aaa bbb

repr() and ``

Python 2.x 中反引号``相当于repr函数的作用,Python 3.x 中去掉了这种写法,只允许使用repr函数。

  • python2
>>> str = 'aaa'
>>> print(`str`)
'aaa'
>>> print(repr(str))
'aaa'
  • python3
>>> str = 'aaa'
>>> print(repr(str))
'aaa'
>>> print(`str`)
  File "<stdin>", line 1
    print(`str`)
          ^
SyntaxError: invalid syntax
>>>

编码

Python2 的默认编码是 asscii,Python 3 默认编码 UTF-8。

  • python2
>>> import sys
>>> sys.getdefaultencoding()
'ascii'
  • python3
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

试试在python2中使用中文?

ps:我在命令行是可以打印中文的,以下代码放在文件中执行

  • python2
print('我爱中国')
print(repr('我爱中国'))
File "main.py", line 28
SyntaxError: Non-ASCII character '\xe6' in file main.py on line 28, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
  • python2 + # coding=utf-8
# coding=utf-8

print('我爱中国')
print(repr('我爱中国'))
我爱中国
'\xe6\x88\x91\xe7\x88\xb1\xe4\xb8\xad\xe5\x9b\xbd'

即使python2中可以通过# coding=utf-8来支持Unicode,但某些方面依然不行

  • python3
print('我爱中国')
print(repr('我爱中国'))

我爱中国
'我爱中国'

数据类型

True/False

python2中Ture/False是全局变量,可以修改,而Python3中True/False是关键字,不可修改。True/False对应数值中的0和1。

  • python2
>>> True = False
>>> True
False
>>> print(True == 0)
True
>>> print(True == 1)
False
>>>
  • python3
>>> True = False
  File "<stdin>", line 1
SyntaxError: can't assign to keyword
>>> print(True == 1)
True
>>> print(True == 0)
False
>>>

remove long

Py3.X去除了long类型,现在只有一种整型——int

  • python2
>>> i = 10000L
>>> print(i)
10000
>>> i = 10000l
>>> print(i)
10000
>>>
  • python3
>>> i = 10000L
  File "<stdin>", line 1
    i = 10000L
             ^
SyntaxError: invalid syntax
>>> i = 10000l
  File "<stdin>", line 1
    i = 10000l
             ^
SyntaxError: invalid syntax
>>>

add bytes

新增了bytes类型,对应于2.X版本的八位串,定义一个bytes字面量的方法如下:

  • python2
>>> b = b'china'
>>> type(b)
<type 'str'>
>>> print(repr(b))
'china'
>>>
  • python3
>>> b = b'china'
>>> type(b)
<class 'bytes'>
>>> print(repr(b))
b'china'
>>>

str 对象和 bytes 对象可以使用 .encode() (str -> bytes) 或 .decode() (bytes -> str)方法相互转化。

  • python3
>>> b = b'china'
>>> type(b)
<class 'bytes'>
>>> print(repr(b))
b'china'
>>> s = b.decode()
>>> s
'china'
>>> type(s)
<class 'str'>
>>> b1 = s.encode()
>>> b1
b'china'
>>> type(b1)
<class 'bytes'>
>>>

不等运算符

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

Python 3.x中去掉了<>, 只有!=一种写法。

  • python2
>>> print(2 != 3, 2 <> 3)
(True, True)
>>>
  • python3
>>> print(2 != 3, 2 <> 3)
  File "<stdin>", line 1
    print(2 != 3, 2 <> 3)
                     ^
SyntaxError: invalid syntax

raw_input

  • python2
>>> print(raw_input("something:"))
something:10
10
>>>
  • python3
>>> print(raw_input("something:"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined
>>>

rasic

2.x raise语句使用逗号将抛出对象类型和参数分开,3.x取消了这种奇葩的写法,直接调用构造函数抛出对象即可。

Python 2可以使用两种语法,如果我们不在括号中包含异常参数,Python 3会引发一个SyntaxError。

  • python2
>>> raise IOError, "file error"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: file error
>>> raise IOError("file error")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: file error
>>>
  • python3
>>> raise IOError, "file error"
  File "<stdin>", line 1
    raise IOError, "file error"
                 ^
SyntaxError: invalid syntax
>>> raise IOError("file error")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: file error

在2.x时代,所有类型的对象都是可以被直接抛出的,在3.x时代,只有继承自BaseException的对象才可以被抛出。

expect

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

捕获异常的语法由 except exc, var 改为 except exc as var。使用语法except(exc1, exc2) as var可以同时捕获多种类别的异常。 Python 2.6已经支持这两种语法。

except (IOError, ValueError), err:

  • python2
>>> try:
...     raise ValueError("value error")
... except (IOError, ValueError), err:
...     print("Error: ", err)
...
('Error: ', ValueError('value error',))
>>>
  • python3
>>> try:
...     raise ValueError("value error")
... except (IOError, ValueError), err:
  File "<stdin>", line 3
    except (IOError, ValueError), err:
                                ^
SyntaxError: invalid syntax
>>>     print("Error: ", err)

except (IOError, ValueError) as err:

  • python2
>>> try:
...     raise ValueError("value error")
... except (IOError, ValueError) as err:
...     print("Error: ", err)
...
('Error: ', ValueError('value error',))
  • python3
>>> try:
...     raise ValueError("value error")
... except (IOError, ValueError) as err:
...     print("Error: ", err)
...
Error:  value error
>>>

import *

python2中可以在类里或者方法里import *,但是python3中禁止了该语法

ps: 在命令行中即使python2中也不支持该写法

def coords(angle, distance):
    from math import *
    return distance * cos(angle), distance * sin(angle)


print(coords(1, 1))
  • python2
(0.5403023058681398, 0.8414709848078965)
  • python3
File "main.py", line 73
    def coords(angle, distance):
    ^
SyntaxError: import * only allowed at module level
posted @ 2021-01-25 18:32  李帆1998  阅读(258)  评论(0编辑  收藏  举报