其他分享
首页 > 其他分享> > 八、函 数

八、函 数

作者:互联网

函数

1. 定义函数

# 1. 使用 def 定义
# 2. 末尾有冒号,无花括号
# 3. 形参前无数据类型
def greet_user(username):
# 文档字符串,简要阐述功能,每个函数都应该包含,三引号括起,Python使用它们来生成有关程序中函数的文档
    """显示简单的问候语"""
    print(“Hello, ” + username.title() + "!")
    
greet_user('jesse')

=>

Hello, Jesse!

2. 传递实参

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

=>
	
I have a hamster.
My hamster's name is Harry.

(2) 关键字实参

直接在实参中关联名称和值,无需考虑实参顺序

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

(3) 默认值

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’)
describe_pet('willie’)

=>

I have a dog.
My hamster's name is Willie.

(4) 等效的函数调用

可混合使用位置实参/关键字实参和默认值

# 函数定义方式为 def describe_pet(pet_name, animal_type=‘dog’):,这些调用方式都可行:

# 一条名为 Willie 的小狗
describe_pet("willie")
describe_pet(pet_name="willie")

# 一只名为 Harry 的仓鼠
describe_pet("harry", "hamster")
describe_pet(pet_name="harry", animal_type="hamster")
describe_pet(animal_type="hamster", pet_name="harry")

3. 返回值

函数可返回任何类型的值,包括列表和字典等

def build_person(first_name, last_name, age=''):
    """返回一个包含某人信息的字典"""
    person = {'first': first_name, 'last': last_name}
    
# Python将非空字符串解读为True
    if age:
        person['age'] = age
    return person
    
musician = build_person('jimi', 'hendrix', age=27)
print(musician)

=>

{'first': 'jimi', 'last': 'hendrix', 'age': 27}

4. 传递列表

(1) 在函数中修改列表

在函数中对列表做的任何修改都是永久性的

# 每个函数都应只负责一项具体的工作
def print_models(unprinted_designs, completed_models):
    """
    模拟打印每个设计,直到没有未打印的设计为止
    打印每个设计后,都将其转移到列表 completed_models 中
    """
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        
         # 模拟根据设计制作3D打印模型的过程
        print("Printing model: " + current_design)
        completed_models.append(current_design)
# 在程序或模块中可使用两个空行分隔相邻函数


def show_completed_models(completed_models):
    """显示打印好的所有模型"""
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)


unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

=>

Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case

(2) 禁止函数修改列表

向函数传递列表的副本而不是原件

function_name(list_name[:])

5. 传递任意数量的实参

(1) 综合使用位置实参和任意数量实参

必须将接纳任意数量实参的形参放在最后,Python 先匹配位置实参和关键字实参

# 星号创建空元组,并将收到的所有值封装到该元组中
def make_pizza(size, *toppings):
    """概述要制作的比萨"""
    print("\ntoppings: " + str(toppings))
    print("Making a " + str(size)) + "-inch pizza with the following toppings:"
    for topping in toppings:
        print("- " + topping)
        
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

=>


# 元组仅有一个元素时,会打印末尾逗号
toppings: ('pepperoni',)
Making a 16-inch pizza with the following toppings:
- pepperoni

toppings: ('mushrooms', 'green peppers', 'extra cheese')
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

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

接受任意数量的健-值对

# 两个星号创建空字典,并将收到的所有名称-值对都封装到这个字典中
def build_profile(first, last, **user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile
    
user_profile = build_profile('albert', 'einstein', 
# <形参(无引号)> = <实参>
                             location = 'princeton',
                             field = 'physics')
print(user_profile)

=>

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

6. 将函数存储在模块中

(1) 导入模块

模块是扩展名为 .py 的文件

# 将 make_pizza(size, *toppings) 存储在 pizza.py 中,在making_pizzas.py中导入

# 没有后缀名 .py
import pizza
	
# 调用模块中函数的格式:<module_name>.<function_name>
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

(2) 导入函数

1) 导入特定的函数

from pizza import make_pizza:

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

2) 导入模块中的所有函数

导入格式:from module_name import *

from pizza import *:

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

(3) as 指定别名

1) 给模块指定别名

import pizza as p

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

2) 给函数指定别名

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

标签:,name,pet,print,实参,pizza,函数
来源: https://blog.csdn.net/Sally_xy/article/details/122706808