函数
函数:带有名字的代码块,用于完成具体的工作,可随时调用;
定义函数:关键字 def 定义函数,后跟 函数名(): ,缩进为函数体;
调用函数:直接指定函数名以及括号括起来的必要信息;
向函数传递信息:(括号内添加信息),函数会接收到;
实参和形参:(usrename)是形参,("ymj")是实参-即传递给函数的信息;
定义函数
def greet_user():
"""显示简单的问候语,是文档字符串的使用方式"""
print("hello!")
greet_user()#调用函数,这样就调用了???是的,就调用了
#向函数传递信息
def greet_user(username):#括号内的附加信息!!!
"""显示简单的问候语"""
print("hello, " + username.title() + ".")
greet_user("ymj")#调用函数时给username一个指定值即可,相当于提供信息
hello! hello, Ymj.
传递实参
位置实参:调用函数涉及到多个实参,按位置对应输出的就叫位置实参;
位置实参:要注意调用的 实参 顺序与函数定义的 形参 位置要一致;
关键字实参:在调用函数时,直接指定 形参=实参 ,以关键字-值的方式出现;
默认值:定义函数时给形参赋默认值,调用时不重新指定就用默认值;
默认值:这里有2个,大坑!!!,看实例;
等效的函数调用:位置实参、关键字实参、默认值,用哪种都行;
避免实参错误:提供的实参>或<形参,都会导致错误;
#位置实参
def pet_info(pet_type, name):
"""显示宠物信息"""
print("\nI have a " + pet_type + ".")
print("Her name is " + name.title())
pet_info("dog", "xiaochai")
pet_info("cat", "yingduan")
#hahhaha我用字典+for循环也做到啦!
pet = {"dog": "xiaochai", "cat": "yingduan"}
for pet_type, name in pet.items():
print("\nI have a " + pet_type + ".")
print("Her name is " + name.title())
#关键字实参
def pet_info(pet_type, name):
print("\nI have a " + pet_type + ".")
print("Her name is " + name.title())
pet_info(pet_type = "dog", name = "bomei")
pet_info(pet_type = "dog", name = "samoye")
#默认值
def pet_info(name, pet_type = "dog"):
#python默认了如果对第一个形参设置了默认值,后面的也要设置,不然报错!!!
#所以设置默认值的形参,就往后面放!!!
print("\nI have a " + pet_type + ".")
print("Her name is " + name.title())
pet_info(name = "yingduan", pet_type = "cat")
pet_info(name = "samoye")#默认值不需要再放进来!!!,关键字实参,默认值
pet_info("samoye")#等效的函数调用方式,位置实参,默认值
I have a dog. Her name is Xiaochai I have a cat. Her name is Yingduan I have a dog. Her name is Xiaochai I have a cat. Her name is Yingduan I have a dog. Her name is Bomei I have a dog. Her name is Samoye I have a cat. Her name is Yingduan I have a dog. Her name is Samoye I have a dog. Her name is Samoye
返回值
return返回:没有return就没有值???是的,把值存起来; 返回简单值:return 返回值,我有点不懂???为什么要返回值???
可选的实参:对于不一定出现的实参,将其对应的形参设置为空值,移到末尾;
可选的实参:try one try里有一个事例,可以去看看 返回字典:存储多信息,适合返回字典;
函数与while循环结合:
#返回简单值
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
#为什么不直接用print呢?????
def get_formatted_name(first_name, last_name):
"""返回整洁的姓名"""
full_name = first_name + ' ' + last_name
print(full_name.title())
musician = get_formatted_name('jimi', 'hendrix')
#可选实参
def get_formatted_name(first_name, last_name, middle_name = ""):
"""返回整洁的姓名"""
if middle_name:
full_name = first_name + " " + middle_name + " "+ last_name
return full_name.title()
else:
full_name = first_name + " " + last_name
return full_name.title()
musician = get_formatted_name('jimi','hendrix', "lee")
print(musician)
musician = get_formatted_name('jimi','hendrix')
print(musician)
#返回字典
def person(name, age, location):
person_info = {"who":name, "how_old":age, "where":location}
return person_info
person = person("ymj", "22", "Beijing")
#函数接收信息,并把信息传给字典,最终打印出来的就是字典内存储的值
print(person)
#函数与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:")
f_name = input("First name: ")
l_name = input("Last name: ")
formatted_name = get_formatted_name(f_name, l_name)
print("\nHello, " + formatted_name + "!")
Jimi Hendrix Jimi Hendrix Jimi Lee Hendrix Jimi Hendrix {'who': 'ymj', 'how_old': '22', 'where': 'Beijing'} Please tell me your name:
First name:
传递列表
传递列表:直接定义列表即可;
在列表中修改函数:每个函数只负责一项具体的工作,便于修改可无限次调用;
禁止函数修改列表:在调用函数时采用保存副本的方式来禁止更改;
def greet_users(names):#直接在定义函数时将其定义为列表
"""向列表中的每位用户都发出简单的问候"""
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
#在列表中修改函数
def print_models(un_models, com_models):
while un_models:
current_models = un_models.pop()
print("printing models: " + current_models + ".")
com_models.append(current_models)
def show_models(com_models):
for com_model in com_models:
print("The " + com_model.title() + " has been printed.")
un_models = ["abc", "bcd", "def"]
com_models = []
print_models(un_models, com_models)
show_models(com_models)
print(un_models)#此时un_models已经修改,且无法回到原来的版本
print(com_models)
#禁止函数修改列表
def print_models(un_models, com_models):
while un_models:
current_models = un_models.pop()
print("printing models: " + current_models + ".")
com_models.append(current_models)
def show_models(com_models):
for com_model in com_models:
print("The " + com_model.title() + " has been printed.")
un_models = ["abc", "bcd", "def"]
com_models = []
print_models(un_models[:], com_models)
#只是在调用函数时,而不是定义函数时采用[:],此时用的相当于副本
show_models(com_models)
print(un_models)#此时un_models仍然时原来的版本
print(com_models)
传递任意数量的实参
创建空元组: 一个 ✳+名称 就是空元组,元组的符号是括号();
元组:收到的所有值都将存储到元组中,一个形参被赋予了多个实参;
元组:有点不太懂???列表,字典的意义在哪里?
位置实参与任意数量实参结合:先匹配位置实参,然后将其余的实参全部放入到最后一个形参当中,所以要将接纳任意数量实参的形参放在最后;
使用任意数量的关键字实参: 两个✳创建的是字典
return:遇到第一个return就会把值返回到调用的地方;
def make_pizza(*toppings):
print(toppings)
for topping in toppings:
print(topping)
make_pizza("abc")
make_pizza("bcd", "def", "cdf")
#位置实参与任意数量实参结合
def make_pizza(size, *toppings):
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#任意数量的关键字实参
def user_info(first, last, **other_info):#创建空字典
info = {}#创建空字典,存储用户的姓名信息
info["first_name"] = first
info["last_name"] = last
for key, value in other_info.items():#遍历字典
info[key] = value #将字典中的每一对值都存入到info中去
return info
user = user_info("mj", "y", location = "china", field = "HRS")
print(user)
('abc',) abc ('bcd', 'def', 'cdf') bcd def cdf Making a 16-inch pizza with the following toppings: - pepperoni Making a 12-inch pizza with the following toppings: - mushrooms - green peppers - extra cheese {'first_name': 'mj', 'last_name': 'y', 'location': 'china', 'field': 'HRS'}
将函数存储在模块中
模块:函数存储的独立文件,使用时可将模块导入到主程序中;
导入整个模块:导入的函数模块需要与应用函数的文件位于同一目录下;
导入整个模块:导入,import module_name;
导入整个模块:调用函数,module_name.function_name();
导入特定的函数:from module_name import function_name;
导入特定的函数:调用时无需使用句点,直接function_name();
导入特定的函数:可以导入任意数量的函数,用逗号分隔即可;
使用as给函数指定别名:from module_name import function_name as fn;
使用as给函数指定别名:函数名的别名,小名哈哈;
使用as给模块指定别名:模块的小名哈哈,import module_name as mn;
使用as给模块指定别名:调用时其余都不变,mn.function_name();
导入模块中的所有函数:用✳即可,from pizza import * ;
导入模块中的所有函数:可通过名称随意调用,无需用句点表示法;
导入模块中的所有函数:还是不要这样做比较好,因为名称容易混淆;
#导入整个模块
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
#导入,应用即可,位于同一目录下,注意应用函数的方式
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#导入特定函数
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#使用as给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
#使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#导入模块中的所有函数
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
函数编写指南
描述型名称,便于理解;
函数后有注释,文档字符串格式,便于理解;
给形参指定默认值时,等号两边不要有空格;
和函数调用时的关键字实参,也不应有空格;
若参数很多,可在括号后按回车键,分多行;
若包含多个函数,应用两个空行将相邻函数分开;
所有的import语句都应放在文件开头;