python学习笔记—14—函数

  1. 函数

(1) len与my_len

python 复制代码
str = "supercarrydoinb"

def my_len(tmp_str):
    cnt = 0
    for i in tmp_str:
        cnt += 1
    return cnt

str_len_1 = len(str)
str_len_2 = my_len(str)
print(f"len = {str_len_1}")
print(f"my_len = {str_len_2}")

(2) 函数传参数量不受限制

(3) 函数未写返回值,则返回None空

(4) None的应用

  1. 在if判断过程中,None等同与false
python 复制代码
def check_age(age):
    if age >= 18:
        return True

if not check_age(16):
    print("你是未成年,不能进网吧")
  1. 声明无内容变量
python 复制代码
age = None

(5) 函数说明文档------函数的注释

python 复制代码
def add(a, b):
    """
    求两数a和b相加的和
    :param a: 累加的参数1
    :param b: 累加的参数2
    :return: 两数累加的结果
    """
    result = a + b
    return result

add(10, 20)

(6) global 在函数内部声明局部变量为全局变量

python 复制代码
def add(a, b):
    """
    求两数a和b相加的和
    :param a: 累加的参数1
    :param b: 累加的参数2
    :return: 两数累加的结果
    """
    global c
    c = 1
    result = a + b
    return result

add(10, 20)
print(f"c = {c}")

(7) 函数案例

python 复制代码
def main_fun():
    print("----------------主菜单------------------")
    print("查询余额 [输入1]")
    print("存款    [输入2]")
    print("取款    [输入3]")
    print("退出    [输入4]")
    num = int(input("请输入您的选择"))
    return num

def print_balance():
    print(f"{name},您好,您的余额剩余{money}元")

def check_balance():
    print("---------------余额查询-----------------")
    print_balance()

def saving_account():
    global money
    tmp_money = int(input("请输入您的存款金额"))
    money += tmp_money
    print("---------------存款-----------------")
    print(f"{name},您好,您存款{tmp_money}元成功")
    print_balance()

def withdraw_money():
    global money
    tmp_money = int(input("请输入您的取款金额"))
    money -= tmp_money
    print("---------------取款-----------------")
    print(f"{name},您好,您取款{tmp_money}元成功")
    print_balance()

if __name__ == '__main__':
    name = None
    money = 500000

    name = input("请输入您的姓名")

    while True:
        print()
        tmp_num = main_fun()
        if tmp_num == 1:
            check_balance()
        elif tmp_num == 2:
            saving_account()
        elif tmp_num == 3:
            withdraw_money()
        elif tmp_num == 4:
            break
相关推荐
汇能感知2 小时前
光谱相机自动调焦曝光控制
经验分享·笔记·科技
W.KN3 小时前
PyTorch 数据类型和使用
人工智能·pytorch·python
虾饺爱下棋3 小时前
FCN语义分割算法原理与实战
人工智能·python·神经网络·算法
千册3 小时前
python+pyside6+sqlite 数据库测试
数据库·python·sqlite
悠哉悠哉愿意6 小时前
【电赛学习笔记】MaixCAM 的OCR图片文字识别
笔记·python·嵌入式硬件·学习·视觉检测·ocr
nbsaas-boot7 小时前
SQL Server 窗口函数全指南(函数用法与场景)
开发语言·数据库·python·sql·sql server
Catching Star7 小时前
【代码问题】【包安装】MMCV
python
摸鱼仙人~7 小时前
Spring Boot中的this::语法糖详解
windows·spring boot·python
Warren987 小时前
Java Stream流的使用
java·开发语言·windows·spring boot·后端·python·硬件工程
_Kayo_8 小时前
VUE2 学习笔记5 动态绑定class、条件渲染、列表过滤与排序
笔记·学习