文章目录
1. 定义函数:函数是带名字的代码块,用于完成具体的工作。要执行函数定义的特定任务,可调用该函数
def greet_user():
print("Hello!")
greet_user()
#输出:Hello!
2. 传递实参及多次调用
def describe_pet(pet_name,animal_type):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}'")
describe_pet('xiaoqiao','cat')
#输出I have a cat
#My cat's name is Xiaoqiao'
def describe_pet(pet_name,animal_type):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}'")
describe_pet('xiaoqiao','cat')
describe_pet('xiaohei','cat')
#输出I have a cat.
#My cat's name is Xiaoqiao'
#I have a cat.
#My cat's name is Xiaohei'
#注:位置实参的顺序很重要,一个实参对应于一个形参。
3. 可给形参指定默认值
def describe_pet(pet_name,animal_type = 'cat'):
print(f"I have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}'")
describe_pet('xiaoqiao')
describe_pet('xiaohei')
#输出I have a cat.
#My cat's name is Xiaoqiao'
#I have a cat.
#My cat's name is Xiaohei'
4. 返回值:在函数中,可使用return语句将值返回到调用函数的代码行
def get_formatted_name(first_name,last_name):
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('ding','yuchuan')
#print(musician)
#输出Ding Yuchuan
5. 返回字典
def build_person(first_name,last_name):
person = {'first':first_name,'last':last_name}
return person
musician = build_person('ding','yuchuan')
print(musician)
#输出{'first': 'ding', 'last': 'yuchuan'}
6. 传递列表
def greet_users(names):
for name in names:
msg = f"Hello,{name.title()}!"
print(msg)
usernames = ['dingyuchaun','chensida','dongyansong']
greet_users(usernames)
#输出Hello,Dingyuchaun!
#Hello,Chensida!
#Hello,Dongyansong!
7. 将函数储存在模块中 ‘import’:使用函数的优点之一就是可以将代码与主程序分离
将函数存储在称为模块的独立文件中,再将模块导入到主程序中。
导入整个模块:import + 指定模块名,就可以在程序中使用该模块中的所有函数。
导入特定的函数:from 指定模块名 import 指定函数 as 简化。
注:如果函数的名称太长,可指定简短而独一无二的别名。
导入模块中的所有函数:from 指定模块名 import *。
8. 函数编写指南
编写函数时,应给函数指定描述性名称,且只在其中使用小写字母和下划线(描述性名称可以帮助你和别人明白代码想要做什么)。
每个函数都应包含简要地阐述其功能的注释。该注释应紧跟在函数定义后面。