python里面的函数
生活随笔
收集整理的這篇文章主要介紹了
python里面的函数
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
python里面的函數(shù)
函數(shù)定義
def my_abs(x):if x >= 0:return xelse:return -x如果沒有return語句,函數(shù)執(zhí)行完畢后也會返回結(jié)果,只是結(jié)果為None。
return None可以簡寫為return。
在Python交互環(huán)境中定義函數(shù)時,注意Python會出現(xiàn)...的提示。函數(shù)定義結(jié)束后需要按兩次回車重新回到>>>提示符下。空函數(shù)
如果想定義一個什么事也不做的空函數(shù),可以用pass語句:
def nop():passpass語句什么都不做,那有什么用?實(shí)際上pass可以用來作為占位符,比如現(xiàn)在還沒想好怎么寫函數(shù)的代碼,就可以先放一個pass,讓代碼能運(yùn)行起來。
pass還可以用在其他語句里,比如:
if age >= 18:pass缺少了pass,代碼運(yùn)行就會有語法錯誤。
返回多個值
比如在游戲中經(jīng)常需要從一個點(diǎn)移動到另一個點(diǎn),給出坐標(biāo)、位移和角度,就可以計(jì)算出新的新的坐標(biāo):
import mathdef move(x, y, step, angle=0):nx = x + step * math.cos(angle)ny = y - step * math.sin(angle)return nx, nyimport math語句表示導(dǎo)入math包,并允許后續(xù)代碼引用math包里的sin、cos等函數(shù)。
然后,我們就可以同時獲得返回值:
>>> x, y = move(100, 100, 60, math.pi / 6) >>> print(x, y) 151.96152422706632 70.0但其實(shí)這只是一種假象,Python函數(shù)返回的仍然是單一值:
>>> r = move(100, 100, 60, math.pi / 6) >>> print(r) (151.96152422706632, 70.0)原來返回值是一個tuple!但是,在語法上,返回一個tuple可以省略括號,而多個變量可以同時接收一個tuple,按位置賦給對應(yīng)的值,所以,Python的函數(shù)返回多值其實(shí)就是返回一個tuple,但寫起來更方便。
默認(rèn)參數(shù)
def repeat_str(s, times = 1): repeated_strs = s * times return repeated_strs repeated_strings = repeat_str("Happy Birthday!") print(repeated_strings)repeated_strings_2 = repeat_str("Happy Birthday!" , 4) print(repeated_strings_2)
#不能在有默認(rèn)參數(shù)后面跟隨沒有默認(rèn)參數(shù) #f(a, b =2)合法 #f(a = 2, b)非法
#關(guān)鍵字參數(shù): 調(diào)用函數(shù)時,選擇性的傳入部分參數(shù) def func(a, b = 4, c = 8): print('a is', a, 'and b is', b, 'and c is', c)
func(13, 17) func(125, c = 24) func(c = 40, a = 80)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎
總結(jié)
以上是生活随笔為你收集整理的python里面的函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html 图片防盗链,【反防盗链】介绍一
- 下一篇: 【OpenCV 例程200篇】67. 空