Python2和3语法区别
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Python2和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 /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。