python进阶(5)--函数
文档目录:
一、函数体
二、实参与形参
三、返回值
四、举例:函数+while循环
五、举例:列表/元组/字典传递
六、模块与函数的导入
---------------------------------------分割线:正文--------------------------------------------------------
一、函数体
1、定义删除
def green_user():
"""显示简单的问候语"""
print("hello world!")
green_user()
查看结果:
hello world!
2、函数传递信息
def green_user(username):
"""显示简单的问候语"""
print( f"Hello,{username.title()}!" )
green_user("Lucy")
查看结果:
Hello,Lucy!
二、实参与形参
1、概念
def green_user(username):
"""显示简单的问候语"""
print( f"Hello,{username.title()}!" )
green_user("Lucy")
形参:username
实参:"Lucy"
2、位置实参,且支持多次调用
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('dog','Mary')
describe_pet('cat','Little White')
查看结果:
I have a dog
My dog's name is Mary
I have a cat
My cat's name is Little White
3、实参中将名称和值关联起来
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(animal_type='dog',pet_name='Mary')
查看结果:
I have a dog
My dog's name is Mary
4、默认值,需放在形参最后
def describe_pet(pet_name,animal_type='cat'):
"""显示宠物的信息"""
print(f"I have a {animal_type}")
print(f"My {animal_type}'s name is {pet_name}")
describe_pet(pet_name='Mary')
describe_pet('Big White')
查看结果:
I have a cat
My cat's name is Mary
I have a cat
My cat's name is Big White
三、返回值
1、返回简直值:return
def get_formatted_name(first_name,last_name):
"""返回全名,并且首字母大写"""
full_name=f"{first_name} {last_name}"
return full_name.title()
name=get_formatted_name("mike","jackson")
print(name)
查看结果:
Mike Jackson
2、实参可选
def get_formatted_name(first_name,last_name,middle_name=''):
"""返回全名,并且首字母大写"""
full_name=f"{first_name} {middle_name} {last_name}"
return full_name.title()
name1=get_formatted_name("mike","jackson",'midddd')
name2=get_formatted_name("mike","jackson")
print(name1)
print(name2)
3、返回字典
def build_person(first_name,last_name):
"""返回一个字段"""
persion={'first':first_name,'last':last_name}
return persion
dicttest1=build_person('xiao','long')
print(dicttest1)
查看结果:
{'first': 'xiao', 'last': 'long'}
四、举例:函数+while循环
def get_formatted_name(first_name,last_name):
"""返回全名,并且首字母大写"""
full_name=f"{first_name} {last_name}"
return full_name.title()
while True:
print("Please tell me your name:")
print("(enter 'q' at any time to quit)")
f_name=input("First name:")
if f_name=='q':
break
l_name=input("Last name:")
if l_name=='q':
break
formatted_name=get_formatted_name('mike','jackson')
print(f"\nhello,{formatted_name}!")
查看结果:
Please tell me your name:
(enter 'q' at any time to quit)
First name:mike
Last name:jackson hello,Mike Jackson!
Please tell me your name:
(enter 'q' at any time to quit)
First name:tom
Last name:q
五、举例:列表/元组/字典传递
1、传递列表
def greet_users(names):
"""向列表中的每位用户发出简单的问候"""
for name in names:
msg=f"Hello,{name.title()}!"
print(msg)
username=['bk','anna','tom','mary']
greet_users(username)
查看结果:
Hello,Bk!
Hello,Anna!
Hello,Tom!
Hello,Mary!
2、在函数中修改列表
unconfirmed_users=['alice','brian','candace']
confirmed_users=[] def confirmed(unconfirmed_users,confirmed_users):
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print( f"Verfying users:{current_user.title()}" )
confirmed_users.append( current_user )
# 显示所有验证的用户
def print_confirmed_users(confirmed_users):
print( "\nThe following users have been confirmed!" )
for confirm_user in confirmed_users:
print( confirm_user.title() ) confirmed(unconfirmed_users,confirmed_users)
print_confirmed_users(confirmed_users)
print(unconfirmed_users)
查看结果:
Verfying users:Candace
Verfying users:Brian
Verfying users:Alice The following users have been confirmed!
Candace
Brian
Alice
[]
3、优化:函数修改原列表
#将列表的副本传递给函数
unconfirmed_users=['alice','brian','candace']
confirmed_users=[] def confirmed(unconfirmed_users,confirmed_users):
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print( f"Verfying users:{current_user.title()}" )
confirmed_users.append( current_user )
# 显示所有验证的用户
def print_confirmed_users(confirmed_users):
print( "\nThe following users have been confirmed!" )
for confirm_user in confirmed_users:
print( confirm_user.title() ) confirmed(unconfirmed_users[:],confirmed_users)
print_confirmed_users(confirmed_users)
print(unconfirmed_users)
查看结果:原列表不会修改
Verfying users:Candace
Verfying users:Brian
Verfying users:Alice The following users have been confirmed!
Candace
Brian
Alice
['alice', 'brian', 'candace']
4、传递任意数量的实参(元组)
#*号可以生成一个空元组,封装接收的所有值
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms','chesse','green peppers')
查看结果:
('pepperoni',)
('mushrooms', 'chesse', 'green peppers')
5、结合使用位置实参和任意数量实参
def make_pizza(size,*toppings):
"""打印顾客点的所有配料"""
print(f"Making a {size}-inch pizza with the folowing toppings")
for topping in toppings:
print(f'-{topping}')
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','chesse','green peppers')
查看结果:
Making a 16-inch pizza with the folowing toppings
-pepperoni
Making a 12-inch pizza with the folowing toppings
-mushrooms
-chesse
-green peppers
6、使用任意数量的关键字实参(字典)
#**可以生成一个空字典
def build_profile(first,last,**user_info):
"""创建一个字典,其中包含有关用户的信息"""
user_info['first_name']=first
user_info['last_name']=last
return user_info
user_profile=build_profile('albert','master',location='princeton',field='physics',number=1)
print(user_profile)
查看运行结果:
{'location': 'princeton', 'field': 'physics', 'number': 1, 'first_name': 'albert', 'last_name': 'master'}
六、模块与函数的导入
1、导入模块
import test04_function
test04_function.make_pizza(13,'prpperono')
test04_function.make_pizza(10,'prpperono','cheese','mushrooms')
查看结果:
Making a 13-inch pizza with the folowing toppings
-prpperono
Making a 10-inch pizza with the folowing toppings
-prpperono
-cheese
-mushrooms
2、导入特定的函数
from test04_function import make_pizza
make_pizza(10,'prpperono','cheese','mushrooms')
3、使用as给函数指定别名
from test04_function import make_pizza as mp
mp(10,'prpperono','cheese','mushrooms')
4、使用as给模块执行别名
import test04_function as pizza
pizza.make_pizza(10,'prpperono','cheese','mushrooms')
5、导入模块中的所有函数
from test04_function import *
python进阶(5)--函数的更多相关文章
- Python进阶(三)----函数名,作用域,名称空间,f-string,可迭代对象,迭代器
Python进阶(三)----函数名,作用域,名称空间,f-string,可迭代对象,迭代器 一丶关键字:global,nonlocal global 声明全局变量: 1. 可以在局部作用域声明一 ...
- Python进阶(二)----函数参数,作用域
Python进阶(二)----函数参数,作用域 一丶形参角度:*args,动态位置传参,**kwargs,动态关键字传参 *args: 动态位置参数. 在函数定义时, * 将实参角度的位置参数聚合 ...
- Python进阶(一)----函数
Python进阶(一)----函数初识 一丶函数的初识 什么函数: 函数是以功能为导向.一个函数封装一个功能 函数的优点: 1.减少代码的重复性, 2.增强了代码的可读性 二丶函数的结构 ...
- Python进阶07 函数对象
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 秉承着一切皆对象的理念,我们再次回头来看函数(function).函数也是一个对象 ...
- Python进阶04 函数的参数对应
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 我们已经接触过函数(function)的参数(arguments)传递.当时我们根 ...
- python进阶之函数和类内建魔法属性
前言 关于对象的魔法方法我们已经讲得太多,但是对于类或函数内建的魔法属性和功能我们涉及较少,下面系统了解一下类和函数的内建属性. 查看内建属性 class Person(object): pass d ...
- Python 进阶 之 函数对象
Python的世界里,万物皆对象,函数当然也是: 首先要定义一个函数: def add(a,b): print a+b 其次定义一个字典来引用该函数: dic = {"add":a ...
- Python进阶-Ⅷ 匿名函数 lambda
1.匿名函数的引入 为了解决那些功能很简单的需求而设计的一句话函数 def func(i): return 2*i # 简化之后 func = lambda i:2*i #todo 其中:func是函 ...
- Python进阶04函数的参数对应
我们已经接触过函数(function)的参数(arguments)传递.当时我们根据位置,传递对应的参数.我们将接触更多的 参数传递方式. 回忆一下位置传递: def f(a,b,c): return ...
- python 进阶篇 函数装饰器和类装饰器
函数装饰器 简单装饰器 def my_decorator(func): def wrapper(): print('wrapper of decorator') func() return wrapp ...
随机推荐
- 机器人行业数据闭环实践:从对象存储到 JuiceFS
JuiceFS 社区聚集了来自各行各业的前沿科技用户.本次分享的案例来源于刻行,一家商用服务机器人领域科技企业. 商用服务机器人指的是我们日常生活中常见的清洁机器人.送餐机器人.仓库机器人等.刻行采用 ...
- 聊聊GLM基座模型的理论知识
概述 大模型有两个流程:预训练和推理. 预训练是在某种神经网络模型架构上,导入大规模语料数据,通过一系列的神经网络隐藏层的矩阵计算.微分计算等,输出权重,学习率,模型参数等超参数信息. 推理是在预训练 ...
- .NET Conf China 2023 活动纪实 抢先看
今天2023年12月16日.NET Conf China 2023举办的日子,北京昨天上午还在飘起雪花,到今天早上的天气就有了极大的改观,大清早就能看到外面徐徐升起的朝阳,这也预示着今天将是一个大 ...
- Lucas定理 、斯特灵公式
斯特灵公式是一条用来取n阶乘的近似值的数学公式. 公式为: 用该公式我们可以用来估算n阶乘的值:估算n阶乘的在任意进制下的位数. 如何计算在R进制下的位数:我们可以结合对数来计算,比如十进制就是lg( ...
- 前端 JS 安全对抗原理与实践
作者:vivo 互联网安全团队- Luo Bingsong 前端代码都是公开的,为了提高代码的破解成本.保证JS代码里的一些重要逻辑不被居心叵测的人利用,需要使用一些加密和混淆的防护手段. 一.概念解 ...
- Sql整理
1:数据库 数据库是以某种有组织的方式存储的数据集合. 保存有组织数据的容器,通常是一个文件或者一组文件. SQL 是Structured Query Language (结构化查询语言)的缩写. 2 ...
- ESXi6.7物理机安装之网卡驱动封装Realtek PCIe GBE Family Controller =瑞昱r8168网卡驱动
https://blog.whsir.com/post-3423.html "我这里先提供一个ESXI6.5封装好的r8168网卡驱动ESXI6.5u2.iso,如果你的网卡也是这个,可以直 ...
- 如何用.net制作一个简易爬虫抓取华为应用市场数据
公司最近要做一款手机,手机需要制作一个应用市场.那么问题来了,自己制作应用市场,数据从哪来呢?作为一个创业型公司.搜集数据变成为了难题. 于是突然想到能不能通过程序去抓取别人应用市场的数据-- 那么我 ...
- LeetCode141环形链表I、II
141. 环形链表 给定一个链表,判断链表中是否有环. 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始). 如果 pos 是 -1,则在该链表中没有环. ...
- 昇腾CANN 7.0 黑科技:大模型训练性能优化之道
本文分享自华为云社区<昇腾CANN 7.0 黑科技:大模型训练性能优化之道>,作者: 昇腾CANN . 目前,大模型凭借超强的学习能力,已经在搜索.推荐.智能交互.AIGC.生产流程变革. ...