第八章 函数
学习目标:
掌握基本的函数功能
如何使用函数处理数据
学习将函数存储在模块的独立文件中
一:定义函数
1.基本框架
def greet_user():
"""显示简单的问候语"""
print("hello!")
great_user()
开头def告诉python需要定义一个函数
其中函数名为greet_user(),定义以冒号结尾
great_user()的工作就是打印hello
2.向函数传递信息
def greet_user(username):
print("hello,"+username.title()+"!")
greet_user("Jesse")
hello,Jesse!
3.实参和形参
在定义函数greet_user()时,变量username是一个形参,上述例子中“Jesse”是实参,实参在被调用时将信息传递给形参,其具体的数值储存在username中
二:传递实参
1.位置实参
实参关联时最简单的方式就是基于实参的顺序
def describe_pet(animal_type,pet_name):
print("\nI have a "+animal_type +".")
print("my "+aniaml_type "'s name is" +"pet_name.title()"+".")
describe_pet('hamster','Herry')
I have a hamster
my hamster's name is Herry
调用函数多次(在调用时要注意顺序)
def describe_pet(animal_type,pet_name):
print("\nI have a "+animal_type +".")
print("my "+aniaml_type "'s name is" +"pet_name.title()"+".")
describe_pet('hamster','Herry')
describe_pet('dog','Willie')
2.关键字实参
传递给函数的名称—值对
在此时实参的顺序无关紧要
def describe_pet(animal_type,pet_name):
print("\nI have a "+animal_type +".")
print("my "+aniaml_type "'s name is" +"pet_name.title()"+".")
describe_pet(animal_type='hamster',pet_name='Harry')
3.默认值
def describe_pet(animal_type=dog,pet_name):
print("\nI have a "+animal_type +".")
print("my "+aniaml_type "'s name is" +"pet_name.title()"+".")
describe_pet("pet_name=Willie")
4.等效的函数调用
当指定默认值或者使用关键字实参顺序无关紧要,从而引发的几种等效调用。
5.避免实参错误
实参个数不匹配等问题
三:返回值
1.返回简单值
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)
Jimi Hendrix
2.让实参变成可选的
不是所有的对象都有middle_name
def get_formatted_name(first_name,middle_name,last_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('john','lee','hooker')
print(musician)
John Lee Hooker
3.返回字典
def build_person(first_name,last_name):
person={'first':first_name,'last':last_name}
return person
musician=build_person('jimi','hendrix')
print(musician)
注:函数接受简单的文本信息,将其放入合适的数据结构种方便之后的处理
def build-person(first_name,last_name,age='')
person={'first':first_name,'last':last_name}
if age:
person['age']=age
return person
musician=build_person('jimi','hendrix',age=17)
print(musician)
上述增加功能:添加年龄信息且可修改
4.结合使用while循环
def get_formatted_name(first_name,last_name):
full_name=first_name+" "+last_name
return full_name.title()
while True:
print("(enter 'q'at any time to quit)")
f_name=input("First name: ")
if f_name=='q':
l_name=input("last name ")
l_name=='q'
formatted_name=get_formatted_name(f_name,l_name)
print("\nHello,"+formatted_name+"!")