python从入门到实践-8章函数

#!/user/bin/env python
# -*- coding:utf-8 -*-

# 给形参指定默认值时,等号两边不要有空格 def function_name("parameter_0",parameter_1='default value')
# 函数形参的位置很重要 传递参数使用关键字实参(一一对应的传递,可以不用理会顺序)
# 默认值传递时候要指定传递(可以对应位置传递)
# 返回值return 默认函数已经结束了

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)

# 结合while写函数

# 向函数传递列表 for循环提取
def greet_user(names):
for name in names:
msg = 'hello ' + name.title()
print(msg)
user_names = ['hannah','ty','margot']
greet_user(user_names)

# 函数中修改列表就是调用列表方法修改
'''【遇到禁止修改源文件的列表,就要用[:]创建一个副本进行修改】'''

# 传递任意数量的实参用: *
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')

# 传递任意数量的关键字参数
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)

# 导入模块 每个py文件都可以是模块
# import 模块
# from 模块 import 函数
# from 模块 import 函数 as 另一个名字
# import 模块 as 另一个名字
# from 模块 import * 导入模块中所有函数

# 所有import都要放在开头,除非在文件开头使用了注释性语言来描述整个程序

 

posted @ 2018-10-30 22:17  alfred_hong  阅读(172)  评论(0编辑  收藏  举报