Python学习(6) ----- Python2和Python3的区别

Python2 和 Python3 是两个主要版本的 Python 编程语言,它们之间有许多重要的区别。Python3 是对 Python2 的一次重大升级,不完全兼容旧版本。以下是它们的主要区别:


🧵 基本语法差异

1. 打印语法

  • Python2:print 是一个语句

    python 复制代码
    print "Hello, world"
  • Python3:print() 是一个函数

    python 复制代码
    print("Hello, world")

2. 整数除法

  • Python2:两个整数相除默认是整数除法

    python 复制代码
    print 5 / 2    # 输出 2
  • Python3:两个整数相除默认是浮点除法

    python 复制代码
    print(5 / 2)   # 输出 2.5

Python2 中想要浮点除法需使用 from __future__ import division。


3. Unicode 处理

  • Python2:字符串默认是 ASCII 编码,str 类型是字节串,unicode 类型才是 Unicode。
  • Python3:字符串默认是 Unicode,str 类型是 Unicode,bytes 类型是字节串。

📦 标准库和内建函数

4. range() 和 xrange()

  • Python2:

    • range() 返回列表
    • xrange() 返回生成器(更节省内存)
  • Python3:只有 range(),行为类似 Python2 的 xrange()


5. input() 函数

  • Python2:input() 相当于 eval(raw_input()),不安全;推荐用 raw_input()
  • Python3:input() 相当于 Python2 的 raw_input(),始终返回字符串

🔧 语言特性

6. 异常语法

  • Python2:

    python 复制代码
    try:
        pass
    except Exception, e:
        print e
  • Python3:

    python 复制代码
    try:
        pass
    except Exception as e:
        print(e)

7. 类的定义

  • Python2:有旧式类和新式类(需继承 object)

    python 复制代码
    class MyClass:     # 旧式类
        pass
    class MyClass(object):  # 新式类
        pass
  • Python3:所有类都是新式类,统一继承自 object


🧪 其他重要差异

8. 字典方法的返回值

  • Python2:

    python 复制代码
    d = {'a': 1}
    print d.keys()   # 返回 list
  • Python3:

    python 复制代码
    d = {'a': 1}
    print(d.keys())  # 返回 dict_keys 对象(可迭代视图)

9. 编码声明

  • Python2 源码需声明编码(默认 ASCII):

    python 复制代码
    # -*- coding: utf-8 -*-
  • Python3 默认 UTF-8,可以不写编码声明(推荐保留)


✅ 总结

特性 Python2 Python3
打印语法 print 语句 print() 函数
除法行为 整除(除非引入 future) 浮点除法
字符串默认类型 ASCII (str) Unicode (str)
range() 列表 可迭代对象(生成器)
input() eval(raw_input()) 字符串
类定义 有旧式和新式类 统一为新式类
异常写法 except Exception, e except Exception as e

❗ Python2 已停止官方支持

自 2020 年 1 月 1 日 起,Python2 已停止维护,不再接收安全更新或 bug 修复。新项目建议全面使用 Python3。


相关推荐
一隅论数智3 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
XiHongShi20163 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
爱吃苹果的日记本3 天前
离散数学第六课
学习·离散数学
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python