当前位置: 首页 > news >正文

【Python】 Function

函数的作用

1 定义函数

在 Python 中,可以使用 def 语句来定义函数。
定义函数的基本语法:

def 函数名(参数列表):函数体return 返回值

def 关键字:用于声明一个函数的开始。
函数名:是你给这个函数起的名字,遵循 Python 的命名规则,如不能以数字开头,不能包含空格等。
参数列表:是函数的输入参数,可以有多个,用逗号分隔。也可以没有参数。在函数调用时,会将对应的值传递给这些参数。
冒号:不能少
函数体:是函数的具体实现代码,也就是函数要执行的操作。函数体需要缩进(通常是 4 个空格),以表示它们属于这个函数。
return 语句:用于从函数中返回值。如果函数没有返回值,可以省略 return 语句,或者使用 return 不带值,此时函数会返回 None

2 函数参数

形参与实参

  • 形参:形参是在函数定义时函数名后面括号中的变量名。它们是函数的 “占位符”,用于表示函数需要接收的参数。例如,在函数定义 def add(a, b): 中,a 和 b 就是形参。它们在函数内部代表了调用时传入的值,用于函数的具体操作。
    形参的个数和顺序在函数定义时就已经确定,函数的调用者需要按照这个定义来提供对应的实参。

  • 实参:实参是在函数调用时传递给函数的具体值。当调用一个函数时,需要将实参传递给函数,实参的值会被赋给对应的形参,然后函数使用这些形参的值来执行相应的操作。例如,在函数调用 add(3, 5) 中,3 和 5 就是实参。它们的值分别被赋给形参 a 和 b,函数会根据这些实参的值进行加法运算。

def multiply(a, b):  # a 和 b 是形参result = a * breturn resultx = 4
y = 7
product = multiply(x, y)  # x 和 y 是实参,它们的值 4 和 7 被传递给形参 a 和 b
print(product)  # 输出 28

函数 multiply 定义了两个形参 a 和 b。当调用函数时,x 和 y 的值作为实参传递给函数。函数内部使用形参 a 和 b
来进行乘法运算,并返回结果。

def get_formatted_name(first_name, last_name):"""Return a full name, neatly formatted."""full_name = f"{first_name} {last_name}"return full_name.title()musician = get_formatted_name('jimi', 'hendrix')
print(musician)

实参传递方式1:位置参数传递

位置参数传递 :这是最常用的传递方式,实参按照函数定义时形参的顺序依次传递。例如上面的例子中,x 对应 a,y 对应 b。下面例子中'hamster' 对应 animal_type'harry' 对应 pet_name

def describe_pet(animal_type, pet_name):"""Display information about a pet."""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")describe_pet('hamster', 'harry') # 位置实参

位置参数对应形式参数,位置错误,可能导致输出错误。

def describe_pet(animal_type, pet_name):"""Display information about a pet."""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")describe_pet('dog', 'willie')
describe_pet('willie', 'dog')

输出:

I have a dog.
My dog’s name is Willie.
I have a willie.
My willie’s name is Dog.

实参传递方式2:关键字参数传递

关键字实参可以无需考虑函数调用中实参的顺序,关键字实参=两边无空格

def describe_pet(animal_type, pet_name):"""Display information about a pet."""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster',)

I have a hamster.
My hamster’s name is Harry.
I have a hamster. My
hamster’s name is Harry.

实参传递方式3:默认参数值

给每个参数指定默认值,在调用函数中,给形参提供了实参时,python 使用指定的实参值,否则使用形参的默认值。因此在形参制定默认值时,可以在函数调用中省略相应的实参。

def describe_pet(pet_name, animal_type='dog'):"""Display information about a pet."""print(f"\nI have a {animal_type}.")print(f"My {animal_type}'s name is {pet_name.title()}.")describe_pet(pet_name='willie')

上面例子中,如任何情况下都要给pet_name提供实参,指定该实参时可使用位置方式,也可使用关键字方式。

如果要描述的动物不是小狗,还必须给animal_type提供参数,可以使用位置方式,也可使用关键字方式。

实参传递方式4:可变参数

通过默认参数实现可变参数

def get_formatted_name(first_name, last_name, middle_name=''):"""Return a full name, neatly formatted."""if middle_name:full_name = f"{first_name} {middle_name} {last_name}"else:full_name = f"{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)

Jimi Hendrix
John Lee Hooker

*variable :传递任意数量的实参

形参*toppings让python创建一个名为topping的空元祖,并将收到的所有值都封装到这个元组中。

def make_pizza(*toppings):"""Print the list of toppings that have been requested."""print(toppings)make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

输出元组

(‘pepperoni’,)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)

def make_pizza(*toppings):"""Summarize the pizza we are about to make."""print("\nMaking a pizza with the following toppings:")for topping in toppings:print(f"- {topping}")make_pizza('pepperoni')
make_pizza('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

混合使用位置参数和任意数量实参

def make_pizza(size, *toppings):"""Summarize the pizza we are about to make."""print(f"\nMaking a {size}-inch pizza with the following toppings:")for topping in toppings:print(f"- {topping}")make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

**variable:传递任意数量的实参

def build_profile(first, last, **user_info):"""Build a dictionary containing everything we know about a user."""user_info['first_name'] = firstuser_info['last_name'] = lastreturn user_infouser_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)

混合*variable和**variable

def print_args(*args, **kwargs):print("Positional arguments:", args)print("Keyword arguments:", kwargs)print_args(1, 2, 3, name = "Alice", age = 25)
# 输出:
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 25}

3 参数为列表

允许函数修改列表

将列表传递给参数后,函数就可对齐进行修改,这种修改时永久性的。
不使用函数修改列表

# Start with some designs that need to be printed.
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []# Simulate printing each design, until none are left.
#  Move each design to completed_models after printing.
while unprinted_designs:current_design = unprinted_designs.pop()print(f"Printing model: {current_design}")completed_models.append(current_design)# Display all completed models.
print("\nThe following models have been printed:")
for completed_model in completed_models:print(completed_model)

使用函数修改列表

def print_models(unprinted_designs, completed_models):"""Simulate printing each design, until none are left.Move each design to completed_models after printing."""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):"""Show all the models that were printed."""print("\nThe following models have been printed:")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)

禁止函数修改列表

切片表示将列表副本传递给函数,向函数传递列表的副本而不是原件

function_name(List_name[:])

4 返回值

返回简单值

def get_formatted_name(first_name, middle_name, last_name):"""Return a full name, neatly formatted."""full_name = f"{first_name} {middle_name} {last_name}"return full_name.title()musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)

返回字典

def build_person(first_name, last_name, age=None):"""Return a dictionary of information about a person."""person = {'first': first_name, 'last': last_name}if age:person['age'] = agereturn personmusician = build_person('jimi', 'hendrix', age=27)
print(musician)

5 函数结合while

无限循环

def get_formatted_name(first_name, last_name):"""Return a full name, neatly formatted."""full_name = f"{first_name} {last_name}"return full_name.title()# This is an infinite loop!
while True:print("\nPlease tell me your name:")f_name = input("First name: ")l_name = input("Last name: ")formatted_name = get_formatted_name(f_name, l_name)print(f"\nHello, {formatted_name}!")

定义推出条件

def get_formatted_name(first_name, last_name):"""Return a full name, neatly formatted."""full_name = f"{first_name} {last_name}"return full_name.title()# This is an infinite loop!
while True:print("\nPlease tell me your name:")print("(enter 'q' at any time to quit)")f_name = input("First name: ")if f_name == 'q':breakl_name = input("Last name: ")if l_name == 'q':breakformatted_name = get_formatted_name(f_name, l_name)print(f"\nHello, {formatted_name}!")

6 将函数存储在模块中

def make_pizza(size, *toppings):"""Summarize the pizza we are about to make."""print(f"\nMaking a {size}-inch pizza with the following toppings:")for topping in toppings:print(f"- {topping}")

import pizza

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

from pizza import make_pizza

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

from pizza import make_pizza as mp

import pizza as p

from pizza import *

http://www.dtcms.com/a/263024.html

相关文章:

  • 计算整数二进制中1的个数
  • 障碍感知 | 基于3D激光雷达的三维膨胀栅格地图构建(附ROS C++仿真)
  • day47 注意力热图可视化
  • 展示折线图的后端数据连接
  • leetcode427.建立四叉树
  • 利润才是机器视觉企业的的“稳定器”,机器视觉企业的利润 = (规模经济 + 技术差异化 × 场景价值) - 竞争强度
  • ViT与CLIP:图像×文本 多模态读心术揭秘
  • 大数据系统架构实践(三):Hbase集群部署
  • 嘉讯科技:医疗信息化、数字化、智能化三者之间的关系和区别
  • EPLAN 中定制 自己的- A3 图框的详细指南(一)
  • 【机器学习深度学习】适合微调的模型选型指南
  • DAOS集群部署-Docker模式
  • CloudBase AI Toolkit 让我用“嘴”开发出的第一款网页游戏
  • 网络安全运维与攻防演练综合实训室解决方案
  • 服务器被入侵的常见迹象有哪些?
  • CentOS服务器SSH远程连接全指南
  • HarmonyOS NEXT应用元服务常见列表操作多类型列表项场景
  • 2025年数字信号、计算机通信与软件工程国际会议(DSCCSE 2025)
  • Excel 如何让表看起来更清晰、专业,而不是花里胡哨?
  • 低功耗MM32L0180系列MCU
  • 【Kafka】docker 中配置带 Kerberos 认证的 Kafka 环境(全过程)
  • [springboot系列] 探秘 JUnit 5:现代 Java 单元测试利器
  • Spring Boot 实现不同用户不同访问权限
  • 基于uniapp的老年皮肤健康管理微信小程序平台(源码+论文+部署+安装+售后)
  • 跨时间潜运动迁移以实现操作中的多帧预测
  • Instrct-GPT 强化学习奖励模型 Reward modeling 的训练过程原理实例化详解
  • nifi1.28.1集群部署详细记录
  • 大语言模型LLM在训练/推理时的padding
  • 用户行为序列建模(篇十一)-小结篇(篇一)
  • 如何读取运行jar中引用jar中的文件