python從入門到實踐-8章函數(shù)
#!/user/bin/env python
# -*- coding:utf-8 -*-
# 給形參指定默認(rèn)值時,等號兩邊不要有空格 def function_name("parameter_0",parameter_1='default value')
# 函數(shù)形參的位置很重要 傳遞參數(shù)使用關(guān)鍵字實參(一一對應(yīng)的傳遞,可以不用理會順序)
# 默認(rèn)值傳遞時候要指定傳遞(可以對應(yīng)位置傳遞)
# 返回值return 默認(rèn)函數(shù)已經(jīng)結(jié)束了
def get_formatted_name(frist_name,last_name,middle_name=''):
if middle_name:
full_name = frist_name + ' ' + middle_name + ' ' + last_name
else:
full_name = frist_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
musician = get_formatted_name('jimi','li','men')
print(musician)
# 返回字典
def build_person(frist_name, last_name):
person = {'frist': frist_name, 'last': last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
# 結(jié)合while寫函數(shù)
# 向函數(shù)傳遞列表 for循環(huán)提取
def greet_user(names):
for name in names:
msg = 'hello ' + name.title()
print(msg)
user_names = ['hannah','ty','margot']
greet_user(user_names)
# 函數(shù)中修改列表就是調(diào)用列表方法修改
'''【遇到禁止修改源文件的列表,就要用[:]創(chuàng)建一個副本進行修改】'''
# 傳遞任意數(shù)量的實參用: *
def make_pizza(size, *topings):
print("\nMaking a " + str(size) + "-inch pizza with following toppings")
for toping in topings:
print("- " + toping)
make_pizza(16, 'pepperoni')
make_pizza(12,'mushrooms', 'green peppers')
# 傳遞任意數(shù)量的關(guān)鍵字參數(shù)
def build_proflie(frist, last, **user_info):
profile = {}
profile['frist_name'] = frist
profile['last_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_proflie('albert','einstein',
location='princeton',
field='physics')
print(user_profile)
# 導(dǎo)入模塊 每個py文件都可以是模塊
# import 模塊
# from 模塊 import 函數(shù)
# from 模塊 import 函數(shù) as 另一個名字
# import 模塊 as 另一個名字
# from 模塊 import * 導(dǎo)入模塊中所有函數(shù)
# 所有import都要放在開頭,除非在文件開頭使用了注釋性語言來描述整個程序

浙公網(wǎng)安備 33010602011771號