⑴ 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.
⑵ python中函數與變數之間的位置怎麼確定
這樣理解吧,如果運行之後你的字元串改變了,那就是放在後面寫。
如果只是獲取你的字元串的一些屬性的話,那就放在前面。
⑶ python如何定義和調用函數
自定義函數用
def 函數名(參數):
(縮進)寫具體的函數部分,和寫普通程序一樣,只不過用return來返回需要的結果。
主程序裡面和使用普通內置函數一樣,函數名(參數)。
⑷ 在python中定義函數
涉及到狀態保存,可以使用函子(書上這么翻譯的,不曉得其他人是不是也這樣叫),給你個例子,你比對著改。如果不懂,自己再延這個方向去查看資料。
classStrip:
def__init__(self,characters):#初始化,將需要保留的狀態信息存起來
self.characters=characters
def__call__(self,string):#創建的函子被使用時,自動調用__call__
returnstring.strip(self.characters)
#下面是使用方法,兩個語句是密切銜接的。
strip_punctution=Strip(',;:.!?')#字元串參數將被__init__吃進去,並且保留在class中,
#相當於一種狀態保存的方法,在你的例子中,你可以將用戶表達式通過這種方式保存起來
strip_punctution('helloworld!')#return'helloworld',他的功能是剝離characters
#字元串中出現的字元,此處把感嘆號去掉了,
#這就是函子典型的使用方法,class中的__call__函數被自動調用,在你的
#例子中,你可以通過這樣的方式調用函數,就不用每次重新輸入表達式了。
⑸ python里函數的定義
定義:
def 函數名(形參1,形參2='初始定義的內容'):
函數中執行的內容
調用:
函數名(實參1)或函數名(形參2=實參2,形參1=實參1)或函數名(實參1,實參2)
⑹ Python中定義函數的使用方法
4.6. 定義函數
我們可以創建一個用來生成指定邊界的斐波那契數列的函數:
>>> def fib(n): # write Fibonacci series up to n
... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ')
... a, b = b, a+b
... print()
...
>>> # Now call the function we just defined:
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
關鍵字 def 引入了一個函數 定義。在其後必須跟有函數名和包括形式參數的圓括弧。函數體語句從下一行開始,必須是縮進的。
函數體的第一行語句可以是可選的字元串文本,這個字元串是函數的文檔字元串,或者稱為 docstring。(更多關於 docstrings 的信息請參考 文檔字元串) 有些工具通過 docstrings 自動生成在線的或可列印的文檔,或者讓用戶通過代碼交互瀏覽;在你的代碼中包含 docstrings 是一個好的實踐,讓它成為習慣吧。
函數 調用 會為函數局部變數生成一個新的符號表。確切的說,所有函數中的變數賦值都是將值存儲在局部符號表。變數引用首先在局部符號表中查找,然後是包含函數的局部符號表,然後是全局符號表,最後是內置名字表。因此,全局變數不能在函數中直接賦值(除非用 global 語句命名),盡管他們可以被引用。
函數引用的實際參數在函數調用時引入局部符號表,因此,實參總是 傳值調用 (這里的 值 總是一個對象 引用 ,而不是該對象的值)。[1] 一個函數被另一個函數調用時,一個新的局部符號表在調用過程中被創建。
一個函數定義會在當前符號表內引入函數名。函數名指代的值(即函數體)有一個被 Python 解釋器認定為 用戶自定義函數 的類型。 這個值可以賦予其他的名字(即變數名),然後它也可以被當作函數使用。這可以作為通用的重命名機制:
>>> fib
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89
如果你使用過其他語言,你可能會反對說:fib 不是一個函數,而是一個方法,因為它並不返回任何值。事實上,沒有 return 語句的函數確實會返回一個值,雖然是一個相當令人厭煩的值(指 None )。這個值被稱為 None (這是一個內建名稱)。如果 None 值是唯一被書寫的值,那麼在寫的時候通常會被解釋器忽略(即不輸出任何內容)。如果你確實想看到這個值的輸出內容,請使用 print() 函數:
⑺ python如何在命令行定義函數
Python在命令行定義函數的方法如下:
打開電腦運行窗體,輸入cmd,點擊確定
命令行窗口,輸入python,進入python命令行,編寫函數後,敲兩次回車,即定義好了函數
測試函數可以正常使用
更多Python相關技術文章,請訪問Python教程欄目進行學習!以上就是小編分享的關於python如何在命令行定義函數的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!
⑻ python怎麼快速定位函數位置
使用pycharm然後直接使用F12就可以直接轉到函數定位位置
也可以使用Structure查看函數,直接就可以定位到函數位置
⑼ Python如何定義一個函數
沒注意 把x y改成 a b 應該滿足題目了
def divideExactly(x, y):
list1 = []
for i in range(x, y):
if i % 7 == 0:
if i % 5 != 0:
list1.append(i)
l = ','.join(str(i) for i in list1)
print(l)
divideExactly(10, 100)