本文記錄了初學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程序設計有所幫助。
新聞熱點
疑難解答
圖片精選