python 小技巧

Python 程序员需要知道的 30 个技巧

这30个小技巧很有用!写程序越发优雅了,强烈推广!

贴士#9. 调试脚本

我们可以在 <pdb> 模块的帮助下在 Python 脚本中设置断点,下面是一个例子:

importpdb
pdb.set_trace()

我们可以在脚本中任何位置指定 <pdb.set_trace()> 并且在那里设置一个断点,相当简便。

贴士#13. 运行时检测 Python 版本

当正在运行的 Python 低于支持的版本时,有时我们也许不想运行我们的程序。为达到这个目标,你可以使用下面的代码片段,它也以可读的方式输出当前 Python 版本:

importsys
#Detect the Python version currently in use.
if not hasattr(sys, "hexversion") or sys.hexversion != 50660080:
    print("Sorry, you aren't running on Python 3.5n")
    print("Please upgrade to 3.5.n")
    sys.exit(1)
 
#Print Python version in a readable format.
print("Current Python version: ", sys.version)

或者你可以使用 sys.version_info >= (3, 5) 来替换上面代码中的 sys.hexversion != 50660080 ,这是一个读者的建议。

在 Python 2.7 上运行的结果:

Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.8.2] onlinux
 
Sorry, youaren't runningonPython 3.5
 
Pleaseupgradeto 3.5.

 

在 Python 3.5 上运行的结果:

Python 3.5.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] onlinux
 
CurrentPythonversion:  3.5.2 (default, Aug 22 2016, 21:11:05) 
[GCC 5.3.0]

 

贴士#19. 使用 * 运算符(splat operator)来 unpack 函数参数

* 运算符(splat operator)提供了一个艺术化的方法来 unpack 参数列表,为清楚起见请参见下面的例子:

deftest(x, y, z):
    print(x, y, z)
 
testDict = {'x': 1, 'y': 2, 'z': 3} 
testList = [10, 20, 30]
 
test(*testDict)
test(**testDict)
test(*testList)
 
#1-> x y z
#2-> 1 2 3
#3-> 10 20 30


贴士#20. 使用字典来存储选择操作

我们能构造一个字典来存储表达式:

stdcalc = {
    'sum': lambda x, y: x + y,
    'subtract': lambda x, y: x - y
}
 
print(stdcalc['sum'](9,3))
print(stdcalc['subtract'](9,3))
 
#1-> 12
#2-> 6





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值