1.系統(tǒng)函數(shù)
由系統(tǒng)提供,直接拿來用或是導入模塊后使用
a = 1.12386
result = round(a,2)
print(result)
> 1.12
2.自定義函數(shù)
- 函數(shù)是結(jié)構(gòu)化編程的核心
- 使用關(guān)鍵詞
def
來定義函數(shù)
#函數(shù)定義
def funcname(parameter_list):
pass
#1.參數(shù)列表可以沒有
#2.用 return 返回值value, 若無return 語句,則返回none; 函數(shù)內(nèi)部遇到 return 則停止運行
def add(x,y):
result = x + y
return result
#定義函數(shù)時,不可與系統(tǒng)函數(shù)同名
def print_code(code):
print(code)
def hello(name):
return 'Hello, {}!'.format(name)
def hello(name):
return 'Hello, {}!'.format(name)
str1 = input('name = ')
print(hello(str1))
>
name = lmc
Hello, lmc!
- 為函數(shù)添加文檔字符串
def hello(name):
'Welcome for users' # 文檔字符串
return 'Hello, {}!'.format(name)
print(hello.__doc__)
> 'Welcome for users'
2.1 函數(shù)的返回值
- 如果不自定義返回值,則無返回值
- 關(guān)鍵字
return
def test():
print('hello')
return
print('end')
test()
> hello
- 用明確的變量組來接受函數(shù)輸出值,便于后期查看(序列解包),不用元組
def damage(skill1,skill2):
damage1 = skill1 * 3
damage2 = skill2 * 2 + 10
return damage1, damage2
skill1_damage, skill2_damage = damage(3,6)
print(skill1_damage,skill2_damage)
> 9 22
- 標明函數(shù)的返回值
def printer() -> int: # 標明返回值為int型
return 11
# Exception的構(gòu)造函數(shù)
class Exception(BaseException):
# 通過 -> None表明函數(shù)沒有返回值
def __init__(self, *args: object) -> None:
pass
注意:這里只起到標明作用,運行過程中不會影響返回值文章來源:http://www.zghlxwxcb.cn/news/detail-542585.html
def printer() -> str: # 標明返回值為str
return 11 # 實際上為int
a = printer()
print(type(a))
>
<class 'int'>
2.1 函數(shù)的參數(shù)
- 指定賦值調(diào)用,增加可讀性
def add(x,y):
result = x + y
return result
c = add(y=3,x=2) # 指定賦值,與順序無關(guān),可讀性
print(c)
> 5
- 給函數(shù)設置默認參數(shù),不傳參也能可以調(diào)用
# collage已經(jīng)設置默認參數(shù),不傳參即采用默認參數(shù)
def print_files(name,age,gender,collage='liaoning University'):
print('My name is ' + name)
print('I am ' + age)
print('My gender is ' + gender)
print('My school is '+ collage)
print_files('阿衰',str(18),'man')
>
My name is 阿衰
I am 18
My gender is man
My school is liaoning University # 默認參數(shù)
print_files('阿衰',str(18),'man', '怕跌中學')
>
My name is 阿衰
I am 18
My gender is man
My school is 怕跌中學
- 星號參數(shù) 類似于序列解包中的星號變量 接收余下位置的參數(shù)(或全部接收)
def printer(*ele):
print(ele)
d = 11
printer(d)
> (11,) # 輸出的為元組
這里必須有逗號才能是元組 無逗號
(11)
類型為int文章來源地址http://www.zghlxwxcb.cn/news/detail-542585.html
a = (11,)
b = (11)
print(type(a))
print(type(b))
>
<class 'tuple'>
<class 'int'>
- 利用*星號接收更多數(shù)據(jù)
def printer(a, b, *ele):
return ele
tuple1 = printer(1,2,3,4,5)
print(tuple1)
> (3, 4, 5)
def printer(a, b, *ele):
print(ele)
tuple1 = (1,2,3,4,5)
printer(*tuple1)
> (3, 4, 5)
- 雙星號傳遞字典
def hello(greeting = 'Hello', name = 'world'):
print('{}, {}!'.format(greeting, name))
params = {'name': 'bobo', 'greeting': 'well met'}
print()
- 對于星號的使用,能不用最好,一般情況下,也可以達到相同效果
- 多用于:
- 定義的函數(shù),允許可變數(shù)量的參數(shù)
- 調(diào)用函數(shù)時,拆分字典或序列使用
到了這里,關(guān)于python筆記:第六章函數(shù)&方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!