栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 函数基础

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 函数基础

目录
  • Functions
    • `1. 简介`
      • 1.1 `无参数无返回值`
      • 1.2 `有参数无返回值`
      • 1.3 `有参数有返回值`
    • `2. 函数参数``
    • `3. 函数文档`

Functions 1. 简介 1.1 无参数无返回值
def fuc():
    print('hello world!')

fuc()  # hello world!
1.2 有参数无返回值
def fuc(str):
    print(f'hello {}!')

fuc('world')  # hello world!
1.3 有参数有返回值
def fuc(str):
    return f'hello {}!'

print(fuc('world'))  # hello world!
`2. 函数参数``
  • 无默认值
  • 无默认值参数必须赋值,参数赋值顺序与函数定义时参数顺序一致
def my_fancy_calculation(first, second, third):
    return first + second - third 

print(my_fancy_calculation(3, 2, 1))  # 4
# 指定参数赋值
print(my_fancy_calculation(first=3, second=2, third=1))  # 4
  • 给参数加上默认值
  • 有默认值参数可以不赋值,此时该参数为默认值
  • 有多个有默认值参数时,可以指定参数进行赋值,否则值会赋值给其它参数
def my_fancy_calculation(first, second=2, third=1):
    return first + second - third 

print(my_fancy_calculation(3, third=1))  # 4
  • 不要将可变参数作为参数默认值,且在函数中尽量不要修改其值,否则会导致函数不能正常执行功能
3. 函数文档
  • 定义函数时,在第一行用3引号对函数的功能入参、返回进行描述
  • 使用help查看函数文档,jupyter中可使用函数+??查看函数源码
def calculate_sum(val1, val2):
    """This is a longer docstring defining also the args and the return value. 

    Args:
        val1: The first parameter.
        val2: The second parameter.

    Returns:
        The sum of val1 and val2.
        
    """
    return val1 + val2

print(help(calculate_sum))
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001618.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号