1. 程式人生 > >python學習筆記--8.函式的定義與使用

python學習筆記--8.函式的定義與使用

這是在學習Python的時候做的筆記,有些時間了,大概是按照一本挺實用的入門書籍學的,我學習程式設計的思路一般是掌握基礎的變數型別,語法-分支結構 函式呼叫 類建立 結構體定義,記錄一些簡單的例項,剩下的就是需要用什麼百度現學。

對我來說python的優勢是,沒有型別要求,不用宣告,沒有指標,萬能陣列,庫很強大。

我這個順序有點差,應該先說函式定義的,這是最基礎的,關於如何定義函式,引數和返回值

程式碼

# 簡單的定義函式
# region
def greet():
    print('hello')

# 引數
def greet_parameter(name):
    print('welcome '
+name+'!!!') # 帶有預設值的 def describe(name, type = 'dog'): print('you have a ' + type + ' name ' + name) describe('123', 'cat') describe('lilei') # 採用預設引數 # 用於返回值 def getfullname(firstname, secondname): temp = firstname + ' ' + secondname return temp.title() print(getfullname('song', 'yu'
)) # 可選引數 帶有預設 放在引數最後 def getnamechoose(first_name, last_name, caps_look = 0): full_name = first_name + ' ' + last_name if caps_look == 0: return full_name.lower() else: return full_name.title() # 傳遞列表引數 def printname(namelist): for name in namelist: print('welcome '
+ name + '!!') usernames = ['hannah', 'ty', 'margot'] printname(usernames) # 禁止修改的列表 # 呼叫時輸入列表usernames可以在函式中修改 輸入usernames[:]只能修改副本 # 傳入任意數量的引數 # 講所有引數封裝到元組中 def make_pizza(*toppings): print(toppings) s = ' ' for topping in toppings: s = s + topping + '_' print(s) make_pizza('pepperoni') make_pizza('mushrooms', 'green peppers', 'extra cheese') # 混合位置與任意關鍵字實參 def meg(name, password, **userinfo): info = {} info['username'] = name info['userpassword'] = password for key, value in userinfo.items(): info[key] = value return info test = meg('songyu', '123', agent = 'moliz', age = '22') print(test) # endregion