GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Python2.x 与 3​​.x 版本区别 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Python 基础教程
Python 基础教程 Python 简介 Python 环境搭建 Python 中文编码 Python VS Code Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 Python 循环语句 Python While 循环语句 Python for 循环语句 Python 循环嵌套 Python break 语句 Python continue 语句 Python pass 语句 Python Number(数字) Python 字符串 Python 列表(List) Python 元组 Python 字典(Dictionary) Python 日期和时间 Python 函数 Python 模块 Python 文件I/O Python File 方法 Python 异常处理 Python OS 文件/目录方法 Python 内置函数

Python 高级教程

Python 面向对象 Python 正则表达式 Python CGI 编程 Python MySQL Python 网络编程 Python SMTP Python 多线程 Python XML 解析 Python GUI 编程(Tkinter) Python2.x 与 3​​.x 版本区别 Python IDE Python JSON Python AI 绘画 Python 100例 Python 测验
Python time tzset()方法
Python IDE

Python2.x 与 3​​.x 版本区别

Python 的 3​​.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。

为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下相容。

许多针对早期 Python 版本设计的程式都无法在 Python 3.0 上正常执行。

为了照顾现有程式,Python 2.6 作为一个过渡版本,基本使用了 Python 2.x 的语法和库,同时考虑了向 Python 3.0 的迁移,允许使用部分 Python 3.0 的语法与函数。

新的 Python 程式建议使用 Python 3.0 版本的语法。

除非执行环境无法安装 Python 3.0 或者程式本身使用了不支援 Python 3.0 的第三方库。目前不支持 Python 3.0 的第三方库有 Twisted, py2exe, PIL等。

大多数第三方库都正在努力地相容 Python 3.0 版本。即使无法立即使用 Python 3.0,也建议编写相容 Python 3.0 版本的程式,然后使用 Python 2.6, Python 2.7 来执行。

Python 3.0 的变化主要在以下几个方面:


print 函数

print 语句没有了,取而代之的是 print() 函数。 Python 2.6 与 Python 2.7 部分地支持这种形式的 print 语法。在 Python 2.6 与Python 2.7 里面,以下三种形式是等价的:

print "fish"
print ("fish") # 注意print后面有个空格
print("fish") # print()不能带有任何其它参数

然而,Python 2.6 实际已经支持新的 print() 语法,实例如下:

from __future__ import print_function
print("fish", "panda", sep=', ')

如果 Python2.x 版本想使用使用 Python3.x 的 print 函数,可以导入 __future__ 包,该包禁用 Python2.x 的 print 语句,采用 Python3.x 的 print 函数:

实例

>>> list =["a", "b", "c"]
>>> print list    # python2.x 的 print 语句
['a', 'b', 'c']
>>> from __future__ import print_function  # 导入 __future__ 包
>>> print list     # Python2.x 的 print 语句被禁用,使用报错
  File "<stdin>", line 1
    print list
             ^
SyntaxError: invalid syntax
>>> print (list)   # 使用 Python3.x 的 print 函数
['a', 'b', 'c']
>>>

Python3.x 与 Python2.x 的许多兼容性设计的功能可以通过 __future__ 这个包来导入。


Unicode

Python 2 有 ASCII str() 类型,unicode() 是单独的,不是 byte 类型。

现在, 在 Python 3,我们最终有了 Unicode (utf-8) 字符串,以及一个字节类:byte 和 bytearrays。

由于 Python3.x 源码文件默认使用 utf-8 编码,所以使用中文就更加方便了:

>>> 中国 = 'china' 
>>>print(中国) 
china

Python 2.x

>>> str = "我爱北京天安门"
>>> str
'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8'
>>> str = u"我爱北京天安门"
>>> str
u'\u6211\u7231\u5317\u4eac\u5929\u5b89\u95e8'

Python 3.x

>>> str = "我爱北京天安门"
>>> str
'我爱北京天安门'

除法运算

Python 中的除法较其它语言显得非常高端,有套很复杂的规则。Python 中的除法有两个运算符,/ 和 //

首先来说 / 除法:

在 Python 2.x 中 / 除法就跟我们熟悉的大多数语言,比如 Java 和 C ,整数相除的结果是一个整数,把小数部分完全忽略掉,浮点数除法会保留小数点的部分得到一个浮点数的结果。

在 Python 3.x 中 / 除法不再这么做了,对于整数之间的相除,结果也会是浮点数。

Python 2.x:

>>> 1 / 2
0
>>> 1.0 / 2.0
0.5

Python 3.x:

>>> 1/2
0.5

而对于 // 除法,这种除法叫做 floor 除法,会对除法的结果自动进行一个 floor 操作,在 Python 2.x 和 Python 3.x 中是一致的。

python 2.x:

>>> -1 // 2
-1

python 3.x:

>>> -1 // 2
-1

注意的是并不是舍弃小数部分,而是执行 floor 操作,如果要截取整数部分,那么需要使用 math 模块的 trunc 函数

python 3.x:

>>> import math
>>> math.trunc(1 / 2)
0
>>> math.trunc(-1 / 2)
0

异常

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

捕获异常的语法由 except exc, var 改为 except exc as var。

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

  • 1. 在 2.x 时代,所有类型的对象都是可以被直接抛出的,在 3.x 时代,只有继承自BaseException的对象才可以被抛出。
  • 2. 2.x raise 语句使用逗号将抛出对象类型和参数分开,3.x 取消了这种奇葩的写法,直接调用构造函数抛出对象即可。

在 2.x 时代,异常在代码中除了表示程序错误,还经常做一些普通控制结构应该做的事情,在 3.x 中可以看出,设计者让异常变的更加专一,只有在错误发生的情况才能去用异常捕获语句来处理。

Python 2.x: 异常处理语法使用逗号。

try:
    # code
except Exception, e:
    print e

Python 3.x: 异常处理语法使用 as。

try:
    # code
except Exception as e:
    print(e)

xrange() 和 range()

Python 2.x: range() 返回一个列表,而 xrange() 返回一个生成器(更节省内存)。

range(5)  # 返回 [0, 1, 2, 3, 4]
xrange(5)  # 返回 xrange 对象,按需生成数字

Python 3.x: xrange() 被移除,range() 返回一个生成器,节省内存。

range(5)  # 返回一个迭代器,按需生成数字

八进制字面量表示

八进制数必须写成 0o777,原来的形式 0777 不能用了;二进制必须写成 0b111。

新增了一个 bin() 函数用于将一个整数转换成二进制字串。 Python 2.6 已经支持这两种语法。

在Python 3.x中,表示八进制字面量的方式只有一种,就是0o1000。

python 2.x

>>> 0o1000
512
>>> 01000
512

python 3.x

>>> 01000
  File "<stdin>", line 1
    01000
        ^
SyntaxError: invalid token
>>> 0o1000
512

不等运算符

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

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


去掉了repr表达式``

Python 2.x 中反引号``相当于repr函数的作用

Python 3.x 中去掉了``这种写法,只允许使用repr函数,这样做的目的是为了使代码看上去更清晰么?不过我感觉用repr的机会很少,一般只在debug的时候才用,多数时候还是用str函数来用字符串描述对象。

def sendMail(from_: str, to: str, title: str, body: str) -> bool:
    pass

多个模块被改名(根据PEP8)

旧的名字 新的名字
_winreg winreg
ConfigParser configparser
copy_reg copyreg
Queue queue
SocketServer socketserver
repr reprlib

StringIO模块现在被合并到新的io模组内。 new, md5, gopherlib等模块被删除。 Python 2.6已经支援新的io模组。

httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib被合并到http包内。

取消了exec语句,只剩下exec()函数。 Python 2.6已经支援exec()函数。


5.数据类型

1)Py3.X去除了long类型,现在只有一种整型——int,但它的行为就像2.X版本的long

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

>>> b = b'china' 
>>> type(b) 
<type 'bytes'> 

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

>>> s = b.decode() 
>>> s 
'china' 
>>> b1 = s.encode() 
>>> b1 
b'china' 

3)dict的.keys()、.items 和.values()方法返回迭代器,而之前的iterkeys()等函数都被废弃。同时去掉的还有 dict.has_key(),用 in替代它吧 。


6.标准库重组

Python 3.x: 一些模块被重新组织或重命名。例如,urllib、urlparse 被合并为 urllib。

# Python 2.x
import urllib
import urlparse

# Python 3.x
import urllib.parse

7.函数的 iteritems() 和 items()

Python 2.x: 字典有 items() 和 iteritems() 方法,items() 返回一个列表,iteritems() 返回一个迭代器。

d = {'a': 1, 'b': 2}
d.items()     # 返回 [('a', 1), ('b', 2)]
d.iteritems()  # 返回字典的迭代器

Python 3.x: iteritems() 被移除,items() 返回一个字典视图(即一个迭代器)。

d = {'a': 1, 'b': 2}
d.items()     # 返回 dict_items([('a', 1), ('b', 2)])

8. 模块的 __future__ 支持

Python 3.x: 许多 Python 2.x 特性已经被移除,Python 2.x 用户如果想要在代码中提前使用 Python 3.x 的行为,可以使用 __future__ 导入来实现兼容。

from __future__ import print_function

9. 字典的排序

Python 2.x: 字典是无序的(没有保证顺序)。

Python 3.x: 字典是有序的,按照插入顺序保留元素。

10. next() 方法

Python 2.x: next() 是一个函数,通常与 iter() 一起使用。

Python 3.x: next() 是一个内建函数,用法与 Python 2.x 相同,但其参数不同,Python 3.x 中支持通过 next(iterator, default) 来设置默认值。

AI 思考中...
Python time tzset()方法
Python IDE

2 篇笔记 写笔记

  1. #0

       heisenbug601

      601***[email protected]

    191

    打开文件

    原:

    file( ..... )
    或 
    open(.....)

    改为只能用

    open(.....)

    从键盘录入一个字符串

    原:

    raw_input( "提示信息" )

    改为:

    input( "提示信息" )

    在python2.x中raw_input()和input( ),两个函数都存在,其中区别为:

    • raw_input()---将所有输入作为字符串看待,返回字符串类型
    • input()-----只能接收"数字"的输入,在对待纯数字输入时具有自己的特性,它返回所输入的数字的类型(int, float )

    在python3.x中raw_input()和input( )进行了整合,去除了raw_input(),仅保留了input()函数,其接收任意任性输入,将所有输入默认为字符串处理,并返回字符串类型。

    heisenbug601

       heisenbug601

      601***[email protected]

    9年前 (2017-11-04)
  2. #0

       坤少

      763***[email protected]

      参考地址

    114

    map、filter 和 reduce

    这三个函数号称是函数式编程的代表。在 Python3.x 和 Python2.x 中也有了很大的差异。

    首先我们先简单的在 Python2.x 的交互下输入 map 和 filter,看到它们两者的类型是 built-in function(内置函数):

    >>> map
    <built-in function map>
    >>> filter
    <built-in function filter>
    >>>

    它们输出的结果类型都是列表:

    >>> map(lambda x:x *2, [1,2,3])
    [2, 4, 6]
    >>> filter(lambda x:x %2 ==0,range(10))
    [0, 2, 4, 6, 8]
    >>>

    但是在Python 3.x中它们却不是这个样子了:

    >>> map
    <class 'map'>
    >>> map(print,[1,2,3])
    <map object at 0x10d8bd400>
    >>> filter
    <class 'filter'>
    >>> filter(lambda x:x % 2 == 0, range(10))
    <filter object at 0x10d8bd3c8>
    >>>

    首先它们从函数变成了类,其次,它们的返回结果也从当初的列表成了一个可迭代的对象, 我们尝试用 next 函数来进行手工迭代:

    >>> f =filter(lambda x:x %2 ==0, range(10))
    >>> next(f)
    0
    >>> next(f)
    2
    >>> next(f)
    4
    >>> next(f)
    6
    >>>

    对于比较高端的 reduce 函数,它在 Python 3.x 中已经不属于 built-in 了,被挪到 functools 模块当中。

    坤少

       坤少

      763***[email protected]

      参考地址

    9年前 (2018-02-26)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.