導航:首頁 > 編程語言 > python主函數的寫法

python主函數的寫法

發布時間:2022-04-24 08:49:18

1. 如何理解python中的main函數

這個腳本被執行的時候,__name__ 值就是 __main__ ,才會執行 main()函數 如果這個腳本是被 import 的話,__name__的值不一樣。main()函數就不會被調用。 這個句子用來寫既能直接運行,又能給其他python程序import,提供庫調用的腳本

2. Python中的函數是什麼,什麼是主調函數和被調函數,二者之間關系是什麼

主調函數是本身固有的數,被調函數是通過其他數計算出來的
主調函數 調用別的函數實現功能
例如 A是主調函數 B是被調函數
void A()
{
B();
}

3. python主函數問題

當你寫的代碼少感覺不到主函數的優勢,但如果一個項目程序大的話主函數+其他的邏輯自定義的函數就體現出優勢了,你發現控制一部分有錯誤或者你想修改某一部分的邏輯控制就可以快速的找到對應的部分,當然你也可以完全不用函數來寫,不過我敢保證這是很蠢的辦法,非常不便於維護

4. Python的函數都有哪些

Python 函數

函數是組織好的,可重復使用的,用來實現單一,或相關聯功能的代碼段。

函數能提高應用的模塊性,和代碼的重復利用率。你已經知道Python提供了許多內建函數,比如print()。但你也可以自己創建函數,這被叫做用戶自定義函數。

定義一個函數

你可以定義一個由自己想要功能的函數,以下是簡單的規則:

5. python 定義主函數怎麼得到其他函數的參數,求代碼改錯

import
csv
def
values
():
reader
=
csv.reader(open("H:/python_study_data/1.txt",
"rb"),
delimiter
=
"\t")
for
row
in
reader:
chr,
start,
end
=
row[0],
int(row[1]),
int(row[2])
yield
(start,
end)
#return
改為yield生成器
def
main
():
for
start,
end
in
values():
aa
=
end-start
print
aa
if
__name__
==
'__main__':
main()

6. python 定義函數

python 定義函數:
在Python中,可以定義包含若干參數的函數,這里有幾種可用的形式,也可以混合使用:

1. 默認參數
最常用的一種形式是為一個或多個參數指定默認值。

>>> def ask_ok(prompt,retries=4,complaint='Yes or no Please!'):
while True:
ok=input(prompt)
if ok in ('y','ye','yes'):
return True
if ok in ('n','no','nop','nope'):
return False
retries=retries-1
if retries<0:
raise IOError('refusenik user')
print(complaint)

這個函數可以通過幾種方式調用:
只提供強制參數
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?yes
True

提供一個可選參數
>>> ask_ok('OK to overwrite the file',2)
OK to overwrite the fileNo
Yes or no Please!
OK to overwrite the fileno
False

提供所有的參數
>>> ask_ok('OK to overwrite the file?',2,'Come on, only yes or no!')
OK to overwrite the file? test
Come on, only yes or no!
OK to overwrite the file?yes
True

2. 關鍵字參數
函數同樣可以使用keyword=value形式通過關鍵字參數調用

>>> def parrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):
print("--This parrot wouldn't", action, end=' ')
print("if you put",voltage,"volts through it.")
print("--Lovely plumage, the",type)
print("--It's",state,"!")

>>> parrot(1000)
--This parrot wouldn't voom if you put 1000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot(action="vooooom",voltage=1000000)
--This parrot wouldn't vooooom if you put 1000000 volts through it.
--Lovely plumage, the Norwegian Blue
--It's a stiff !
>>> parrot('a thousand',state='pushing up the daisies')
--This parrot wouldn't voom if you put a thousand volts through it.
--Lovely plumage, the Norwegian Blue
--It's pushing up the daisies !

但是以下的調用方式是錯誤的:

>>> parrot(voltage=5, 'dead')
SyntaxError: non-keyword arg after keyword arg
>>> parrot()
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <mole>
parrot()
TypeError: parrot() missing 1 required positional argument: 'voltage'
>>> parrot(110, voltage=220)
Traceback (most recent call last):
File "<pyshell#58>", line 1, in <mole>
parrot(110, voltage=220)
TypeError: parrot() got multiple values for argument 'voltage'
>>> parrot(actor='John')
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <mole>
parrot(actor='John')
TypeError: parrot() got an unexpected keyword argument 'actor'
>>> parrot(voltage=100,action='voom',action='voooooom')
SyntaxError: keyword argument repeated

Python的函數定義中有兩種特殊的情況,即出現*,**的形式。
*用來傳遞任意個無名字參數,這些參數會以一個元組的形式訪問
**用來傳遞任意個有名字的參數,這些參數用字典來訪問
(*name必須出現在**name之前)

>>> def cheeseshop1(kind,*arguments,**keywords):
print("--Do you have any",kind,"?")
print("--I'm sorry, we're all out of",kind)
for arg in arguments:
print(arg)
print("-"*40)
keys=sorted(keywords.keys())
for kw in keys:
print(kw,":",keywords[kw])

>>> cheeseshop1("Limbuger","It's very runny, sir.","It's really very, very runny, sir.",shopkeeper="Michael Palin",client="John",sketch="Cheese Shop Sketch")
--Do you have any Limbuger ?
--I'm sorry, we're all out of Limbuger
It's very runny, sir.
It's really very, very runny, sir.
----------------------------------------
client : John
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
>>>

3. 可變參數列表
最常用的選擇是指明一個函數可以使用任意數目的參數調用。這些參數被包裝進一個元組,在可變數目的參數前,可以有零個或多個普通的參數
通常,這些可變的參數在形參列表的最後定義,因為他們會收集傳遞給函數的所有剩下的輸入參數。任何出現在*args參數之後的形參只能是「關鍵字參數」
>>> def contact(*args,sep='/'):
return sep.join(args)

>>> contact("earth","mars","venus")
'earth/mars/venus'

4. 拆分參數列表
當參數是一個列表或元組,但函數需要分開的位置參數時,就需要拆分參數
調用函數時使用*操作符將參數從列表或元組中拆分出來
>>> list(range(3,6))
[3, 4, 5]
>>> args=[3,6]
>>> list(range(*args))
[3, 4, 5]
>>>

以此類推,字典可以使用**操作符拆分成關鍵字參數

>>> def parrot(voltage,state='a stiff',action='voom'):
print("--This parrot wouldn't", action,end=' ')
print("if you put",voltage,"volts through it.",end=' ')
print("E's", state,"!")

>>> d={"voltage":"four million","state":"bleedin' demised","action":"VOOM"}
>>> parrot(**d)
--This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !

5. Lambda
在Python中使用lambda來創建匿名函數,而用def創建的是有名稱的。
python lambda會創建一個函數對象,但不會把這個函數對象賦給一個標識符,而def則會把函數對象賦值給一個變數
python lambda它只是一個表達式,而def則是一個語句

>>> def make_incrementor(n):
return lambda x:x+n

>>> f=make_incrementor(42)
>>> f(0)
42
>>> f(2)
44

>>> g=lambda x:x*2
>>> print(g(3))
6
>>> m=lambda x,y,z:(x-y)*z
>>> print(m(3,1,2))
4

6. 文檔字元串
關於文檔字元串內容和格式的約定:
第一行應該總是關於對象用途的摘要,以大寫字母開頭,並且以句號結束
如果文檔字元串包含多行,第二行應該是空行

>>> def my_function():
"""Do nothing, but document it.

No, really, it doesn't do anything.
"""
pass

>>> print(my_function.__doc__)
Do nothing, but document it.

No, really, it doesn't do anything.

7. python主函數怎麼寫

一般來說,Python程序員可能是這樣寫main()函數的:
"""Mole docstring.

This serves as a long usage message.
"""import sysimport getoptdef main():
# parse command line options
try:
opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) except getopt.error, msg: print msg print "for help use --help"
sys.exit(2) # process options
for o, a in opts: if o in ("-h", "--help"): print __doc__
sys.exit(0) # process arguments
for arg in args:
process(arg) # process() is defined elsewhereif __name__ == "__main__":
main()

Guido也承認之前自己寫的main()函數也是類似的結構,但是這樣寫的靈活性還不夠高,尤其是需要解析復雜的命令行選項時。為此,他向大家提出了幾點建議。
添加可選的 argv 參數
首先,修改main()函數,使其接受一個可選參數 argv,支持在互動式shell中調用該函數:
def main(argv=None):
if argv is None:
argv = sys.argv # etc., replacing sys.argv with argv in the getopt() call.1234

這樣做,我們就可以動態地提供 argv 的值,這比下面這樣寫更加的靈活:
def main(argv=sys.argv):
# etc.12

這是因為在調用函數時,sys.argv 的值可能會發生變化;可選參數的默認值都是在定義main()函數時,就已經計算好的。
但是現在sys.exit()函數調用會產生問題:當main()函數調用sys.exit()時,互動式解釋器就會推出!解決辦法是讓main()函數的返回值指示退出狀態(exit status)。因此,最後面的那行代碼就變成了這樣:
if __name__ == "__main__":
sys.exit(main())12

並且,main()函數中的sys.exit(n)調用全部變成return n。
定義一個Usage()異常
另一個改進之處,就是定義一個Usage()異常,可以在main()函數最後的except子句捕捉該異常:
import sysimport getoptclass Usage(Exception):
def __init__(self, msg):
self.msg = msgdef main(argv=None):
if argv is None:
argv = sys.argv try: try:
opts, args = getopt.getopt(argv[1:], "h", ["help"]) except getopt.error, msg: raise Usage(msg) # more code, unchanged
except Usage, err: print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help"
return 2if __name__ == "__main__":
sys.exit(main())

這樣main()函數就只有一個退出點(exit)了,這比之前兩個退出點的做法要好。而且,參數解析重構起來也更容易:在輔助函數中引發Usage的問題不大,但是使用return 2卻要求仔細處理返回值傳遞的問題。

8. python如何定義和調用函數

自定義函數用
def 函數名(參數):
(縮進)寫具體的函數部分,和寫普通程序一樣,只不過用return來返回需要的結果。
主程序裡面和使用普通內置函數一樣,函數名(參數)。

9. python怎麼調用c的main函數

if
__name__=="__main__":
print
'main'
當腳本作為執行腳本時__name__的值為__main__當腳本作為模塊時__name__為模塊文件名。舉個例子,a.py作為執行腳本時__name__的值是__main__。有2個腳本,a.py和b.py,a中引入b,執行a.py時,在b中模塊的__name__就是b.py

閱讀全文

與python主函數的寫法相關的資料

熱點內容
linux分區讀取 瀏覽:794
單片機液晶顯示屏出現雪花 瀏覽:890
解壓器用哪個好一點 瀏覽:771
什麼app看小說全免費 瀏覽:503
sha和ras加密 瀏覽:823
韓順平php視頻筆記 瀏覽:636
阿里雲ecs伺服器如何設置自動重啟 瀏覽:596
三星電視怎麼卸掉app 瀏覽:317
如何將pdf轉換成docx文件 瀏覽:32
dos命令批量改名 瀏覽:376
centosphp環境包 瀏覽:601
mfipdf 瀏覽:534
電腦解壓後電腦藍屏 瀏覽:295
外網訪問內網伺服器如何在路由器設置 瀏覽:856
2014統計年鑒pdf 瀏覽:434
linuxoracle用戶密碼 瀏覽:757
股票交易pdf 瀏覽:898
p2papp源碼 瀏覽:308
記錄睡眠軟體app哪個好用 瀏覽:140
液壓助力車壓縮比 瀏覽:217