Home  >  Article  >  Backend Development  >  初学Python实用技巧两则

初学Python实用技巧两则

WBOY
WBOYOriginal
2016-06-16 08:42:21922browse

本文记录了初学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程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn