您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

初学Python实用技巧两则

2024/3/14 5:02:52发布22次查看
本文记录了初学python常用的两则实用技巧,分享给大家供大家参考之用。具体如下:
1.可变参数
示例代码如下:
>>> def powersum(power, *args): ... '''''return the sum of each argument raised to specified power.''' ... total = 0 ... for i in args: ... total += pow(i, power) ... return total ...>>> powersum(2, 3, 4) 25>>> powersum(2, 10) 100
由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典的键/值对。
2.exec语句将字符串str当成有效python代码来执行。execfile(filename [,globals [,locals ]])函数可以用来执行一个文件。
示例代码如下:
>>> exec 'print hello world' hello world>>> execfile(r'c:\test.py') hello,world!
希望本文所述对大家的python程序设计有所帮助。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product