python--函数的返回值、函数的参数

简介: python--函数的返回值、函数的参数

函数的返回值


特性:

  • 减少重复代码
  • 使程序变的可扩展
  • 使程序变得易维护

函数名:命名规则和变量一样

函数的返回值:

return, 函数执行完毕. 不会执行后面逻辑

  • 如果函数中不写return返回None
  • 只写return 返回None
  • return 返回值. 返回一个值
  • return 值1, 值2,... 返回多个值. 调用方接收到的是元组

遇到return结束函数里的语句,下面的不会执行

没有return,返回None

def foo():
    print('foo')
foo  # 表示是函数
foo()  # 表示执行foo函数
def sayhi():  # 函数名
    print("Hello, I'm nobody!")
sayhi()  # 调用函数

结果:

Hello, I'm nobody!

之前写的乘法是这样的

a, b = 5, 8
c = a ** b
print(c)

改成函数之后是这样的

a, b = 5, 8
# 改成用函数写
def calc(x, y):
    res = x ** y
    return res  # 返回函数执行结果
c = calc(a, b)  # 结果赋值给c变量
print(c)

函数和过程

函数有return 过程没有return

# 函数
def func1():
    print('in the func1')
    return 0
# 过程
def func2():
    print('in the func2')
x = func1()
y = func2()
print('from func1 return is %s' % x)
print('from func2 return is %s' % y)

结果:

in the func1
in the func2
from func1 return is 0
from func2 return is None
import time  # 导入time模块
def logger():  # 定义了函数名为logger
    time_format = '%Y-%m-%d %X'  # 时间格式,Y年m月d日X时分秒
    time_current = time.strftime(time_format)  # time.strftime引用上面的时间格式
    with open('ccc.txt', 'a+') as f:
        f.write('%s end action\n' % time_current)  # 将日期时间和end action写入到f里
def aaa():
    print('in the test1')
    logger()
def bbb():
    print('in the test2')
    logger()
def ccc():
    print('in the test3')
    logger()
aaa()
bbb()
ccc()

结果:

in the test1
in the test2
in the test3
ccc.txt里写入
2020-06-15 22:17:37 end action
2020-06-15 22:17:37 end action
2020-06-15 22:17:37 end action
def test():
    print('in the test')
    return 0
    print('end test')
test()

结果:

in the test
# 遇到return结束函数里的语句,下面的不会执行
def test():
    print('in the test')
    return 0
x = test()
print(x)

结果:


         

x=test()先执行函数里的内容,最后将函数里的返回值赋给x

def test():
    print('in the test')
    return 1
print(test())  # 相当于x=test()  print(x)

结果:

in the test
1

没有 return 返回 None

def test():
    print('in the test')
x = test()
print(x)

结果:

in the test
None
def test1():
    print('in the test1')
def test2():
    print('in the test2')
    return 0
def test3():
    print('in the test3')
    return 1, 'hello', {'name': 'zouzou'}
    return test2
x = test1()
y = test2()
z = test3()
print(x)
print(y)
print(z)

结果:

in the test1
in the test2
in the test3
None
0
(1, 'hello', {'name': 'zouzou'})

先执行x,y,z,在打印他们的返回值


函数的参数


  • 关键字参数不能写在位置参数前面(定义函数时)
  • 参数组不能在位置参数和关键字参数前面
  • 默认参数放在最后面

形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元。因此,形参只在函数内部有效。函数调用结束返回主调用函数后则不能再使用该形参变量

实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。因此应预先用赋值,输入等办法使参数获得确定值

def test(x, y):  # x,y叫形参
    print(x)
    print(y)
test(2, 4)  # 位置参数,实参

         
def test(x, y=3):  # y为默认参数
    print(x)
    print(y)
test(2)


参数组


*args接收的位置参数,转换成元组的形式,没有传参返回空元组

**kwargs接收的关键字参数,转换成字典的形式,没有传参返回空字典

def test(**kwargs):  # 参数组,接收的参数不确定时用**
    print(kwargs)
test()

结果:

{}
def test(*args):  # 参数组,接收的参数不确定时用*
    print(args)
test()

结果:

()
def test(x, *args):
    print(x)
    print(args)  # 打印的是一个元组
test(2, 4, 6, 8)
test(*[6, 8, 9, 45, 5])  # args=tuple[6,8,9,45,5]

结果:

2
(4, 6, 8)
6
(8, 9, 45, 5)
def test(**kwargs):  # 参数组,接收的参数不确定时用*  
    print(kwargs)  # 打印的是一个字典
    print(kwargs['name'])
    print(kwargs['age'])
    print(kwargs['job'])
test(name='zou', age=18, job='IT')  # 接收的是关键字参数

结果:

{'name': 'zou', 'age': 18, 'job': 'IT'}
zou
18
IT

相关文章
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
745 2
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
1914 1
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
643 0
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
484 101
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
419 99
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
772 98
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
Python
Python 函数定义
Python 函数定义
1197 155
|
JSON 缓存 开发者
淘宝商品详情接口(item_get)企业级全解析:参数配置、签名机制与 Python 代码实战
本文详解淘宝开放平台taobao.item_get接口对接全流程,涵盖参数配置、MD5签名生成、Python企业级代码实现及高频问题排查,提供可落地的实战方案,助你高效稳定获取商品数据。
|
算法 安全 数据安全/隐私保护
Python随机数函数全解析:5个核心工具的实战指南
Python的random模块不仅包含基础的随机数生成函数,还提供了如randint()、choice()、shuffle()和sample()等实用工具,适用于游戏开发、密码学、统计模拟等多个领域。本文深入解析这些函数的用法、底层原理及最佳实践,帮助开发者高效利用随机数,提升代码质量与安全性。
1683 0

推荐镜像

更多