【320】Python 2.x 与 3.x 的区别

本文介绍了从Python2.x迁移到Python3.x时需要注意的主要差异,包括print函数使用方式的变化、输入函数的不同行为、Tkinter模块名称的更改、除法运算符的功能调整以及如何在不同Python版本间切换。

通过代码移植的报错进行梳理!

 

1. print 函数的区别

  Python 2.x 中可以加空格或者括号,但是 Python 3.x 只能是括号的

# Python 2.x
>>> print "processing..."
processing...
>>> print("processing...")
processing...

# Python 3.x
>>> print("processing...")
processing...

 

2. raw_input 与 input 函数

  Python 2.x 中 raw_input 与 Python 3.x 中 input 函数类似,而 Python 2.x 中的 input 函数接收数字或者带引号字符串

# Python 2.x
>>> a = raw_input("Value: ")
Value: Alex
>>> a
'Alex'
>>> b = input("Value: ")
Value: "Alex"
>>> b
'Alex'

# Python 3.x
>>> a = input("Value: ")
Value: Alex
>>> a
'Alex'

参考:python2.x和python3.x中raw_input( )和input( )区别

 

3. Tkinter 模块

  Python 2.x 为 Tkinter,但是 Python 3.x 为 tkinter(小写)

# Python 2.x
>>> import Tkinter

# Python 3.x
>>> import tkinter

参考:Python GUI编程(Tkinter)

 

4. 除法运算符

  Python 2.x 中 /、// 均为整除,但是 Python 3.x 中 / 表示除以,// 表示整除

# Python 2.x
>>> 77/60
1
>>> 77//60
1

# Python 3.x
>>> 77/60
1.2833333333333334
>>> int(77/60)
1
>>> 77//60
1

 

5. cmd 默认 Python 版本

  需要通过修改环境变量来切换 Python 2.x 和 Python 3.x

参考:如何快速切换Python运行版本,如何选择Python版本

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值