一、函数
1、函数的定义: 用 def 关键字来实现
def greet_user():
"""显示简单的问候语"""
print('hello!')
greet_user()
结果:
hello!
注意: 在def 之后要加冒号;""" xxxxx """ 被称为 文档字符串的注释,描述了函数的做什么的
2、形参 与 实参
在上面例子的基础上做简单修改:
def greet_user(name): # 这个 name 就是形参
"""显示简单的问候语"""
print('Hello, ' + name.title() + "!")
greet_user('jesse') # 这个 'jesse' 就是实参
结果:
Hello, Jesse!
个人理解,形参就是一个代称,目的在于告诉 这个函数 有个值要被传进来,但是具体是什么值并不知道,也就是形式上的参数,没有实际的值。而实参是传递给函数的值,是函数进行操作的实际值,所以叫实参。实参给形参实例化:实参→形参。
3、实参的传递方式
3.1 位置实参:实参的顺序与形参的顺序严格一致
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type + "'s name is " + pet_name.title() + '.')
describe_pet('dog','harry')
describe_pet('cat','willie')
结果:
I have a dog.
My dog's name is Harry.
I have a cat.
My cat's name is Willie.
如果顺序不一致的话,会出现问题,可以发现 这个时候所显示的就不是我们想表达的了
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type + "'s name is " + pet_name.title() + '.')
describe_pet('harry','dog')
describe_pet('willie','cat')
结果:
I have a harry.
My harry's name is Dog.
I have a willie.
My willie's name is Cat.
3.2 关键字实参:以 名称=值 的方式传递参数,不考虑顺序
def describe_pet(animal_type,pet_name):
"""显示宠物的信息"""
print('\nI have a ' + animal_type + '.')
print('My ' + animal_type + "'s name is " + pet_name.title() + '.')
describe_pet(pet_name='willie',animal_type='cat')
结果:
I have a cat.
My cat's name is Willie.
上面这个例子中,传递形式就以 形参名=值 的形式进行
3.3 让实参变成可选的:指定一个默认值--空字符串
有时候我们输入的实参数目是不定的,比如在传递名字的时候,有的人有三个 有的 有两个,特别是外文名字都有frist_name 和 last_name,但是 middle_name 不一定有,所以我们需要实现 实参可选。
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('john', 'lee', 'hooker')
print(musician)
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
结果:
John Hooker Lee
Jimi Hendrix
在由于 middle_name 不一定有,所以就指定成了一个空的字符串 的默认值,在函数中判断一下 是不是有值
4、传递任意数量的实参
4.1 不知道有多少实参:创建空元组(*形参名)
有些时候我们是不知道函数会接收多少个实参,所以就需要有 接收任意数量实参的能力。假设在制作披萨的时候不同客户有不同的配料要求,所以每次的输入参数的数量不定,我们可以这么实现:
def make_pizzs(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizzs('pepperoni')
make_pizzs('mushrooms','green peppers','extra cheese')
结果:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
可以发现,使用 *toppings 生成了一个元组,把每次传进去的实参变成了相应的元组,可以做一下的更改:
def make_pizzs(*toppings):
"""打印顾客点的所有配料"""
print('\nMaking a pizza with the following toppings:')
for topping in toppings:
print('-' + topping)
make_pizzs('pepperoni')
make_pizzs('mushrooms','green peppers','extra cheese')
结果:
Making a pizza with the following toppings:
-pepperoni
Making a pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
4.2 不知道实参的类型:创建空字典(**形参名)
上面的例子是我们不知道会向函数输入多少的实参,但是有时候 我们不知道实参的类型,有时候是数值型 有时候是字符串,所以函数有时候需要有这个能力,我们可以用创建一个空字典来实现:
def build_profile(first, last, **user_info):
proflie = {}
proflie['first_name'] = first
proflie['last_name'] = last
for key, value in user_info.items(): # .items() 函数可以提取字典中的 键-值 对
proflie[key] = value
return proflie
user_profile = build_profile('albert','einstein',
location='princeton',
field='physics')
print(user_profile)
结果:
{'field': 'physics', 'last_name': 'einstein', 'location': 'princeton', 'first_name': 'albert'}
可见,**user_info 创建了一个空字典
二、函数编写指南
1、给函数起一个 描述性的名称 并且使用小写字母及下划线,可以直接从函数的名称就知道函数的功能
2、编写较好的文档字符串("""xxxxxx"""),让别的程序员只需要阅读文档中的描述就能使用这个函数
3、给形参在指定默认值的时候,等号两边最好不要加空格;函数调用时也最好不要加空格
def function_name(parameter_0, parameter_1='default value')
function_name(value_0, parameter_1='value')
4、所有的import都放在程序的开头

本文详细介绍了Python编程中的函数概念,包括函数定义、形参与实参的区别、实参的传递方式(位置实参、关键字实参、默认值及可变数量实参),并提供了函数编写指南,强调了函数命名、文档字符串和参数默认值的设置规范。
1030

被折叠的 条评论
为什么被折叠?



