# Python 2 与 Python 3 的区别示例代码
# 1. print 函数
# Python 2
print "Hello, World!" # 不需要括号
# Python 3
print("Hello, World!") # 需要括号
# 2. 整数除法
# Python 2
result = 3 / 2 # 结果为 1 (整数除法)
print result
# Python 3
result = 3 / 2 # 结果为 1.5 (浮点数除法)
print(result)
# 如果需要在 Python 3 中得到整数除法的结果,可以使用 // 操作符
result = 3 // 2 # 结果为 1
print(result)
# 3. Unicode 字符串
# Python 2
s = 'hello' # 默认是字节字符串
u = u'hello' # Unicode 字符串需要前缀 u
# Python 3
s = 'hello' # 默认是 Unicode 字符串
b = b'hello' # 字节字符串需要前缀 b
# 4. xrange 函数
# Python 2
for i in xrange(5): # xrange 返回一个生成器对象
print i
# Python 3
for i in range(5): # range 返回一个生成器对象
print(i)
# 5. input 函数
# Python 2
name = raw_input("Enter your name: ") # raw_input 返回字符串
print "Hello, " + name
# Python 3
name = input("Enter your name: ") # input 返回字符串
print("Hello, " + name)
# 6. 异常处理
# Python 2
try:
1 / 0
except ZeroDivisionError, e: # 使用逗号分隔异常类型和异常对象
print "Error:", e
# Python 3
try:
1 / 0
except ZeroDivisionError as e: # 使用 as 关键字
print("Error:", e)
上一篇:python整除运算符
下一篇:python四舍五入
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站