天天看点

Python中的函数定义函数传递参数返回值传递列表将函数存储在模块中

文章目录

  • 定义函数
  • 传递参数
  • 返回值
  • 传递列表
  • 将函数存储在模块中

定义函数

下面是一个简单的函数,名为greet_user():

def greet_user():
    """简单的问候语"""
    print("Hi!")
greet_user()
           

python使用关键字def来定义一个函数。函数名为greet_user(),它不需要任何信息就能完成其工作,因此括号是空的(即便如此,括号也必不可少)。最后,定义以冒号结尾。后面的所有缩进行构成了函数体。

传递参数

如下:

Python中的函数定义函数传递参数返回值传递列表将函数存储在模块中

可在函数定义def greet_user()的括号内添加username。通过在这里添加username,就可让函数接受你给username指定的任何值。现在,这个函数要求你调用它时给username指定一个值。

在上述函数中,变量username是一个形参——函数完成其工作所需要的一项信息。在调用时,“kk”是一个实参,是函数调用时传递给函数的信息。

对于实参的传递方式有以下几种:

位置实参

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('hamster', 'harry')

'''
输出:
I have a hamster.
My hamster's name is Harry.
'''
           

关键字实参

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(animal_type='hamster', pet_name='harry')
           

默认值

def describe_pet(pet_name, animal_type='dog'):
	"""显示宠物的信息"""
	print("\nI have a " + animal_type + ".")
	print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')

'''
输出:
I have a dog.
My dog's name is Willie.
'''
           

返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。在函数中,可使用return语句将值返回到调用函数的代码行。返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。

返回简单值

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
'''
           

可选的实参:

def get_formatted_name(first_name, last_name, middle_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('jimi', 'hendrix')
print(musician)
musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
           

返回字典

def build_person(first_name, last_name):
	"""返回一个字典,其中包含有关一个人的信息"""
	person = {'first': first_name, 'last': last_name}
	return person
musician = build_person('jimi', 'hendrix')
print(musician)
           

传递列表

def greet_users(names):
	"""向列表中的每位用户都发出简单的问候"""
	for name in names:
		msg = "Hello, " + name.title() + "!"
		print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

'''
输出:
Hello, Hannah!
Hello, Ty!
Hello, Margot!
'''
           

在函数中修改列表

例如:

# 首先创建一个列表,其中包含一些要打印的设计
unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []
# 模拟打印每个设计,直到没有未打印的设计为止
# 打印每个设计后,都将其移到列表completed_models中
while unprinted_designs:
	current_design = unprinted_designs.pop()
	#模拟根据设计制作3D打印模型的过程
	print("Printing model: " + current_design)
	completed_models.append(current_design)
# 显示打印好的所有模型
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
           

禁止函数修改列表

解决这个问题,可向函数传递列表的副本而不是原件;这样函数所做的任何修改都只影响副本,而丝毫不影响原件。

如:

传递任意数量的实参

def make_pizza(*toppings):
	"""打印顾客点的所有配料"""
	print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

'''
输出:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')
'''
           

将函数存储在模块中

导入整个模块

如:我们将文件pizza.py中除函数make_pizza()之外的其他代码都删除:

def make_pizza(size, *toppings):
	"""概述要制作的比萨"""
	print("\nMaking a " + str(size) +
		"-inch pizza with the following toppings:")
	for topping in toppings:
		print("- " + topping)
           

接下来,我们在pizza.py所在的目录中创建另一个名为making_pizzas.py的文件,这个文件导入刚创建的模块,再调用make_pizza()两次:

import pizza

pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
           

Python读取这个文件时,代码行import pizza让Python打开文件pizza.py,并将其中的所有函数都复制到这个程序中。你看不到复制的代码,因为这个程序运行时, Python在幕后复制这些代码。你只需知道,在making_pizzas.py中,可以使用pizza.py中定义的所有函数。

导入特定函数

from module_name import function_name

from module_name import function_0, function_1, function_2
           

使用 as 给函数指定别名

from module_name import function_name as fn
           

使用 as 给模块指定别名

import module_name as mn
           

导入模块中的所有函数

from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')