[TOC]
定义函数
def greet_user():#函数定义
"""显示简单的问候语"""#文档字符串的注释
print("Hello!")
greet_user()
向函数传递信息
def greet_user(username):
"""问候语"""
print("hello, "+username.title()+"!")
greet_user("jack")#调用函数传参数
实参和形参
函数greet_user()定义中,变量username是一个形参(函数完成其工作所需的一项信息)."Jack"是一个实参.实参是调用函数时传递给函数的信息.
传递实参
函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参.向函数传递实参的方式很多,可以使用位置实参,这要求实参的顺序与形参的顺序相同;也可使用关键字实参,其中每个实参都由变量名和值组成;还可以使用列表和字典.
1.位置实参
调用函数时,Python必须将函数调用的每个实参都关联到函数定义中的一个形参.为此,最简单的关联方式是基于实参的顺序.这种关联方式被称为位置实参.函数可以多次调用.
2.关键字实参
关键字实参是传递给函数的名称-值对.直接在实参中将名称和值关联起来.
返回值
1.返回简单值
def get_formatted_name(first_name,last_name,middle_name=''):#为middle_name指定一个默认值,变成可选参数
"""返回整洁的姓名"""
if middle_name:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)
2.返回字典
函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构.
def build_person(first_name,last_name,age='')
if age:
person = {'first':first_name,'last':last_name,'age':age}
else:
person = {'first':first_name,'last':last_name}
return person
musician = build_person('jimi','hendrix')
print(musician)
3.结合使用函数和while循环
def get_formatted_name(first_name,last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(Enter 'q' at any time to quie)")
f_name = input("First name: ")
if f_name == 'q'
break
l_name = input("Last name: ")
if l_name == 'q'
break
formatted_name = get_formatted_name(f_name,l_name)
print("\nHello, " + formatted_name + "!")
传递列表
def greet_users(names):
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannan','python','malsdgj']
greet_users(usernames)
传递任意数量的实参
def make_pizza(*toppings):
"""打印顾客的所有配料"""
print(toppings)
*toppings形参中的星号让Python创建一个名为toppings的空元组,并将收到的所有值都封装到这个元组中.
使用任意数量的关键字实参
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含我们知道的有关用户的一切"""
profile = {}
profile['first_name'] = first
profile['last_name'] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert','einstein',location='princeton',field='python')
print(user_profile)
将函数储存在模块中
1.导入整个模块
要让函数是可导入的,得先创建模块.模块是扩展名为.py的文件,包含要导入到程序的代码.
#pizza.py
def make_pizza(size,*toppings):
"""概述要制作的披萨"""
print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
#making_pizzas.py
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green pepers','extra cheese')
2.导入特定的函数
导入模块中的特定函数,from module_name import function_0,function_1,function_2
使用这种方式,调用函数时就无需使用句点.直接使用函数即可
3.使用as给函数指定别名
from pizza import make_pizza as mp
mp(16,'peperoni')
4.使用as给模块指定别名
import pizza as p
p.make_pizza(13,'peperoni')
5.导入模块中的所有函数
from module_name import *
函数编写指南
1.见名知意
2.阐述功能的注释,紧跟函数定义后面,采用文档字符串格式
3.给形参指定默认值时,等号两边不要有空格,函数调用中的关键字实参同样.
4.函数和函数之间空两行,易区分.
网友评论