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都要放在开头,除非在文件开头使用了注释性语言来描述整个程序
最新文章
- 程序集与反射技术(C#)
- mysql慢查询日志分析工具 mysqlsla(转)
- 一个请求在Struts2框架中的处理流程
- Java8闭包
- FlashFXP5_gr坑爹的故事
- andriod RadioButton
- 百分比定位加position定位的常用布局
- USB枚举过程(2)
- POJ 3104
- 页面全屏显示JS代码
- URAL 2025. Line Fighting (math)
- poj1969---找规律
- (简单) POJ 2406 Power Strings,扩展KMP。
- 本地修改js代码并时时生效的解决办法
- DOUAudioStreamer 中kqueue的应用
- echarts自定义提示框数据
- Java8的一些新特性
- SQLServer之创建全文索引
- java.text.DateFormat 线程不安全问题
- highcharts-3d.js实现饼状图