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

复习python从入门到实践——函数function

复习python从入门到实践——函数function

函数是特别难的,大家一定要好好学、好好复习、反复巩固。函数没学好,会为后面造成很大困扰。
教科书中函数举例会稍微有点复杂。在此章复习中,我将整理出容易疏漏和混淆的知识点,并用最简单的代码辅助大家理解。
本章涉及:定义函数、实参与形参、return返回值、传递列表与切片、将函数导入模块。

文章目录

  • 复习python从入门到实践——函数function
    • 1. 定义 def函数
      • Syntax:
    • 2.实参与形参:
      • 传递实参的方法:
      • 可选实参:
      • 通过*传递任意数量实参
      • 涉及字典 **可变关键字参数
    • 3.return返回
      • Syntax:
      • Principle:
      • 注意:
    • 4. 传递列表
      • [:]切片含义:
    • 5.将函数导入模块

1. 定义 def函数

Syntax:

def 函数():函数的具体表现(函数体)
函数() #调用

区分函数和变量

  1. 函数 add_numbers():
    接受输入的参数(a,b),并且要有返回值return。后面会介绍。
def add_numbers(a, b):# 定义一个函数return a + bresult = add_numbers(3, 5)#使用函数
print("结果:", result)

2.变量x,y
依靠=储存各种数据。

# 定义两个变量
x = 10
y = 20sum_of_variables = x + y # 使用变量
print("变量之和:", sum_of_variables)

2.实参与形参:

形参类似于中文里概括性质的类别,比如“同学”
实参是具体的例子,比如“小明”属于”同学“,”小明“是实参。

def great_user(username):"""显示问候语:""" #文本注释,三引号,描述函数做什么。print(f"Hello {username.title()}!") #函数的工作
great_user('Ashley') 

username 形参
Ashley 实参

传递实参的方法:

(1)对应位置

def animal_lists(category,name):print(f"My {category}'s name is {name.title()}.")
animal_lists('pig','feifei')

(2)关键词,用’='连接

def animal_lists(category,name):print(f"My {category}'s name is {name.title()}.")
animal_lists(name='feifei',category='pig')

(3)最后一项是默认值

def animal_lists(name, category='dog',):#把默认值放到最后。print(f"My {category}'s name is {name.title()}.")
animal_lists(name='feifei')

可选实参:

把可选可不选的参数放到最后一个
middle_name=’ ’

def formatted_name(first_name,last_name,middle_name=' '):if middle_name:formatted_name = f'{first_name} {middle_name} {last_name}'else:formatted_name = f'{first_name} {last_name}'return formatted_name.title()
students = formatted_name('Haifei',"Wang")
print(students)
students = formatted_name('Haifei','Wang','Pig')#最后一个是中间名
print(students)

通过*传递任意数量实参

def feifei_behaviors(*behavior):#通过加星号调用多个实参print(f'飞飞正在:{behavior}')
feifei_behaviors('拉粑粑')
feifei_behaviors('吃粑粑','吃屎','被茵茵看着拉屎')

涉及字典 **可变关键字参数

def build_profile(first,last,**user_info):#**可变关键字参数,除了First和last"""创建一个字典,其中包含我们知道的有关用户的一切"""profile = {}profile['first_name'] = firstprofile['last_name'] = lastfor key,value in user_info.items():profile[key] = valuereturn profile
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

3.return返回

Syntax:

def function_name():具体的statementreturn statement中的函数

Principle:

== a. The statements after the return() statement are not executed. 在return()语句之后的语句不会被执行。
b. return() statement can not be used outside the function. return()语句不能在函数外部使用。
c. If the return() statement is without any expression, then the NONE value is returned. 如果return()语句没有任何表达式,则返回NONE值。==

举例:

def formatted_name(first_name,last_name):formatted_name = first_name+' '+ last_namereturn formatted_name()
students = formatted_name('Haifei',"Wang")
print(students)

结果: Haifei Wang

如果没有return语句

def formatted_name(first_name,last_name):formatted_name = first_name+' '+ last_name
students = formatted_name('Haifei',"Wang")
print(students)

结果是None

注意:

调用你定义的函数,而不是变量

def city_country(city, country):full_name = f'{city},{country}'return full_namewhile True:print("Please inter the city and country:")city = input('city:')country = input('country:')new_name = city_country(city, country)#调用定义变量print(new_name)	

4. 传递列表

普通方法:
def+循环+发送列表+调用列表

def greating_lists(names):#建立函数 # 问候 '''给列表中的用户打招呼'''for name in names:print(f'Hello! {name.title()}.')
usernames=['feifei','ashley','tony']# 发送列表
greating_lists(usernames)#调用列表-实参

[:]切片含义:

基本:
[start:stop:step]
用数学集合可以表示为:[ )
举例:
[1:4] 从索引1(包含)到索引4(不包含)也就是索引1 2 3 这几个元素。

重要的容易忽略:
表示列表序列
创建副本

original_list = [10, 20, 30, 40, 50]# 使用切片创建副本
copied_list = original_list[:]# 修改副本
copied_list[0] = 100print("Original List:", original_list)
print("Copied List:", copied_list)

原始列表 original_list 并没有被修改。这是因为切片创建了一个新的列表对象,而不是直接引用原始列表。

5.将函数导入模块

Syntax:
from 文件 import 要导入的东西
import 原来的东西名字 as 你想改的名字
from 文件 import *(所有函数)

http://www.lryc.cn/news/276412.html

相关文章:

  • 【Internal Server Error】pycharm解决关闭flask端口依然占用问题
  • torch.nn.functional.interpolate与torchvision.transforms.Resize方法对张量图像Resize应用
  • 【Spring】Spring的事务管理
  • 配置cendos 安装docker 配置阿里云国内加速
  • 【深度学习:Domain Adversarial Neural Networks (DANN) 】领域对抗神经网络简介
  • STM32 ESP8266 物联网智能温室大棚 (附源码 PCB 原理图 设计文档)
  • 【DevOps-08-1】Harbor镜像仓库介绍和安装
  • 第八节 vue3新特性
  • Web前端-jQuery
  • Leetcod面试经典150题刷题记录 —— 二叉搜索树篇
  • 【大数据进阶第三阶段之ClickHouse学习笔记】ClickHouse的简介和使用
  • Linux下Redis6下载、安装和配置教程-2024年1月5日
  • Java后端开发——Ajax、jQuery和JSON
  • ssm基于Vue的戏剧推广网站论文
  • 安卓adb
  • 【数位dp】【动态规划】C++算法:233.数字 1 的个数
  • docker (portainer 安装nginx)
  • 10个linux文件管理命令
  • 实战:使用docker容器化服务与文件挂载-2
  • 联合union
  • 如何在 Umi /Umi 4.0 中配置自动删除 console.log 语句?
  • (生物信息学)R语言绘图初-中-高级——3-10分文章必备——饼图(初级)
  • AI ppt生成器 Tome
  • Linux与Windows下追踪网络路由:traceroute、tracepath与tracert命令详解
  • 图解JVM (及一些垃圾回收\GC相关面试题 持续更新)
  • linux 系统安全及应用
  • 如何查看崩溃日志
  • 使用HttpSession和过滤器实现一个简单的用户登录认证的功能
  • SEO全自动发布外链工具源码系统:自动增加权重 附带完整的搭建安装教程
  • Qt隐式共享浅析