1.系統函式
由系統提供,直接拿來用或是匯入模塊后使用
a = 1.12386
result = round(a,2)
print(result)
> 1.12
2.自定義函式
- 函式是結構化編程的核心
- 使用關鍵詞
def
來定義函式
#函式定義
def funcname(parameter_list):
pass
#1.引數串列可以沒有
#2.用 return 回傳值value, 若無return 陳述句,則回傳none; 函式內部遇到 return 則停止運行
def add(x,y):
result = x + y
return result
#定義函式時,不可與系統函式同名
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!
- 為函式添加檔案字串
def hello(name):
'Welcome for users' # 檔案字串
return 'Hello, {}!'.format(name)
print(hello.__doc__)
> 'Welcome for users'
2.1 函式的回傳值
- 如果不自定義回傳值,則無回傳值
- 關鍵字
return
def test():
print('hello')
return
print('end')
test()
> hello
- 用明確的變陣列來接受函式輸出值,便于后期查看(序列解包),不用元組
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
2.1 函式的引數
- 指定賦值呼叫,增加可讀性
def add(x,y):
result = x + y
return result
c = add(y=3,x=2) # 指定賦值,與順序無關,可讀性
print(c)
> 5
- 給函式設定默認引數,不傳參也能可以呼叫
# collage已經設定默認引數,不傳參即采用默認引數
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 # 默認引數
print_files('阿衰',str(18),'man', '怕跌中學')
>
My name is 阿衰
I am 18
My gender is man
My school is 怕跌中學
- 星號引數 類似于序列解包中的星號變數 接收余下位置的引數(或全部接收)
def printer(*ele):
print(ele)
d = 11
printer(d)
> (11,) # 輸出的為元組
這里必須有逗號才能是元組 無逗號
(11)
型別為int
a = (11,)
b = (11)
print(type(a))
print(type(b))
>
<class 'tuple'>
<class 'int'>
- 利用*星號接收更多資料
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()
- 對于星號的使用,能不用最好,一般情況下,也可以達到相同效果
- 多用于:
- 定義的函式,允許可變數量的引數
- 呼叫函式時,拆分字典或序列使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/556925.html
標籤:其他
上一篇:== 與 equals 的區別?
下一篇:返回列表