Python基础-8-函数
admin
2024-03-15 18:27:16

一:定义函数

#!/bin/python3def greet_user(username):print(f"hello, {username.title()}!")greet_user('jesse')# RESULT
'''
hello, Jesse!
'''

使用关键字def来告诉Python要定义一个函数。这是函数定义,向Python指出了函数名,还可能在圆括号内指出函数为完成任务需要什么样的信息。

二:传递实参

1、位置实参

调用函数时,Python必须将函数调用中的每个实参都关联到函数定义中的一个形参。为此,最简单的关联方式是基于实参的顺序。这种关联方式称为位置实参。

def describe_pet(animal_type, pet_name):print(f"I have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name}.")describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
# RESULT
'''
I have a hamster.
My hamster's name is harry.
I have a dog.
My dog's name is willie.
'''

2、关键字实参

关键字实参是传递函数的名称值对。

describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='dog', pet_name='willie')

3、默认值

def describe_pet(pet_name, animal_type='dog',):print(f"I have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name}.")describe_pet('willie')
# RESULT
'''
I have a dog.
My dog's name is willie.
'''

4、等效的函数调用

describe_pet('willie')
describe_pet(pet_name='willie')describe_pet('willie', 'dog')
describe_pet(pet_name='willie', animal_type='dog')
describe_pet(animal_type='dog', pet_name='willie')

三:返回值

def get_formatted_name(first_name, last_name, middle_name=''):full_name = f"{first_name} {middle_name} {last_name}"return full_name.title()full_name = get_formatted_name('jimi', 'hendrix')
print(full_name) # RESULT
'''
Jimi  Hendrix
'''

四:传递列表

def greet_users(names):for name in names:msg = f"Hello, {name.title()}"print(msg)usernames=['hannah', 'ty', 'margot']
greet_users(usernames)# RESULT
'''
Hello, Hannah
Hello, Ty
Hello, Margot
'''

1、在函数中修改列表

将列表传递给函数后,函数就可对其进行修改。在函数中对这个列表所做的任何修改都是永久性的。

def print_models(unprinted_designs, completed_models):while unprinted_designs:current_design = unprinted_designs.pop()print(f"Printing model: {current_design}")completed_models.append(current_design)def show_completed_models(completed_models):for completed_model in completed_models:print(completed_model)unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
# RESULT
'''
Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case
dodecahedron
robot pendant
phone case
'''

2、禁止函数修改列表

为了解决向函数传递参数并被修改而丢失之前内容的问题,可向函数传递列表的副本而非原件。这样,函数所做的任何修改都只影响副本,而原件丝毫不受影响。

切片表示法[:]创建列表副本,function(list_name[:])

def print_models(unprinted_designs):while unprinted_designs:current_design = unprinted_designs.pop()print(f"Printing model: {current_design}")def show_unprinted_designs(unprinted_designs):for unprinted_design in unprinted_designs:print(f"unprinted designs:{unprinted_design}")unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
print_models(unprinted_designs[:])
show_unprinted_designs(unprinted_designs)
# RESULT
'''
Printing model: dodecahedron
Printing model: robot pendant
Printing model: phone case
unprinted designs:phone case
unprinted designs:robot pendant
unprinted designs:dodecahedron
'''

五:传递任意数量的实参

对于预先不知道函数需要接受多少个实参的时候,Python允许函数从调用语句中收集任意数量的实参。例如函数只有一个形参*toppings

def make_pizza(*toppings):print(toppings)make_pizza('pepperoni')
make_pizza('mushrooms', 'green perppers', 'extra cheese')
# RESULT
'''
('pepperoni',)
('mushrooms', 'green perppers', 'extra cheese')
'''

1、结合使用位置实参和任意数量实参

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

def make_pizza(size, *toppings):print(f"Making a {size}-inch pizza with the following toppings:")for topping in toppings:print(f"- {topping}")make_pizza(15, 'pepperoni')
make_pizza(21, 'mushrooms', 'green perppers', 'extra cheese')
# RESULT
'''
Making a 15-inch pizza with the following toppings:
- pepperoni
Making a 21-inch pizza with the following toppings:
- mushrooms
- green perppers
- extra cheese
'''

2、使用任意数量的关键字实参

有时候,需要接受任意数量的实参,但预先不知道传递给函数的会是什么样的信息。在这种情况,可将函数编写成能够接受任意数量的键值对。

def build_profile(first, last, **user_info):user_info['first_name'] = firstuser_info['last_name'] = lastreturn user_infouser_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)
# RESULT
'''
{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}
'''

函数build_profile()的定义要求提供名和姓,同时允许根据需要提供任意数量的键值对。

形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称值对放到这个字典中。

六:将函数存储在模块中

将函数存储在称为模块的独立文件中,再将模块导入到主程序中。import语句允许在当前运行的程序文件中使用模块中的代码。

1、导入整个模块

要让函数时可导入的,得先创建模块。模块的扩展名为.py文件,包含要导入到程序中的代码。

只需要编写一条import语句并在其中指定模块名,就可在程序中使用该模块中的所有函数。

# pizza.pydef make_pizza(size, *toppings):print(f"Making a {size}-inch pizza with the following toppings:")for topping in toppings:print(f"-{topping}")
# make_pizza.pyimport pizzapizza.make_pizza(15, 'peperoni')
pizza.make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')# RESULT
'''
Making a 15-inch pizza with the following toppings:
-peperoni
Making a 21-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
'''

2、导入特定的函数

还可以导入模块中的特定函数,这种导入方法的语法如下:

from module_name import function_name

通过用逗号分隔函数名,可根据需要从模块中导入任意数量的函数:

from module_name import function_0, function_1, function_2

对于前面的make_pizza.py来说,如果只想导入要使用的函数,可以这样做:

from pizza import make_pizzamake_pizza(15, 'peperoni')
make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

3、使用as给函数指定别名

如果导入函数的名称可能与程序中的现有名称冲突,或者函数名字太长,可指定简短而独一无二的别名:函数的另一个名称,类似于外号。要给函数取这种特殊外号,需要在导入它时指定。

from pizza import make_pizza as making_pizzamaking_pizza(15, 'peperoni')
making_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

4、使用as给模块指定别名

还可以给模块指定别名。

import pizza as pp.make_pizza(15, 'peperoni')
p.make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

5、导入模块中的所有函数

from pizza import *make_pizza(15, 'peperoni')
make_pizza(21, 'mushrooms', 'green peppers', 'extra cheese')

相关内容

热门资讯

如果王楚钦是国乒一哥,那么樊振... 马龙一句“有王楚钦在我们都很心定”的认可还在回响,樊振东在德国杯夺冠并捧起MVP奖杯的照片已经传遍全...
原创 美... 当特朗普在社交平台上敲下已抓获马杜罗这一行字时,曾自诩为自由捍卫者的美国,已彻底揭开了道德的面具,露...
最新或2023(历届)天津各大... 最新或2023(历届)天津各大学理科税收学专业排名及录取分数线天津最新或2023(历届)各高校理科税...
最新或2023(历届)广东各大... 广东最新或2023(历届)各高校理科财务管理专业录取分数线排名专业院校平均分最高分省市文理年份批次财...
新疆区最新或2023(历届)大... 新疆维吾尔自治区招生委员会公布了《自治区最新或2023(历届)普通高校招生各批次最低投档控制分数线》...