初學Python實用技巧兩則
更新時間:2014年08月29日 10:19:17 投稿:shichen2014
這篇文章主要介紹了初學Python實用技巧兩則,包括可變參數(shù)的應用級execfile函數(shù)的用法,需要的朋友可以參考下
本文記錄了初學Python常用的兩則實用技巧,分享給大家供大家參考之用。具體如下:
1.可變參數(shù)
示例代碼如下:
>>> 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變量前有*前綴,所有多余的函數(shù)參數(shù)都會作為一個元組存儲在args中。如果使用的是**前綴,多余的參數(shù)則會被認為是一個字典的鍵/值對。
2.exec語句將字符串str當成有效Python代碼來執(zhí)行。execfile(filename [,globals [,locals ]])函數(shù)可以用來執(zhí)行一個文件。
示例代碼如下:
>>> exec 'print "Hello World"' Hello World>>> execfile(r'c:\test.py') hello,world!
希望本文所述對大家的Python程序設計有所幫助。
相關文章
flask 框架操作MySQL數(shù)據(jù)庫簡單示例
這篇文章主要介紹了flask 框架操作MySQL數(shù)據(jù)庫,結合實例形式詳細分析了flask框架操作MySQL數(shù)據(jù)庫的連接、表格創(chuàng)建、數(shù)據(jù)增刪改查等相關使用技巧,需要的朋友可以參考下2020-02-02

