7. python 函数

函数 def




函数 return 的注意点 和 函数文档



变量的作用域 局部变量 全局变量

# 局部变量
def testA():
    a = 100

    print(a)

testA()



函数的返回值

def test1():
    # return 1, 2 # 默认 返回的是 元组
    # return [10, 20] # 可以 输出 元组、 列表、 字典
    return {'name': 'Python', 'age': 18}

res = test1()

print(res)

函数参数

  1. 位置参数
# 位置参数
def test1(name, age, gender):
    print(f'你的名字{name}, 年龄{age}, 性别{gender}')

test1('TOM', 20, '男')  # 参数一一对应, 传入的参数和形参个数不一致时,会报错

  1. 关键字参数
# 关键字参数
def test1(name, age, gender):
    print(f'你的名字{name}, 年龄{age}, 性别{gender}')

test1('ROSE', age=18, gender='男') 
# 1. 位置参数要放在关键字参数之前,否者会报错
# 2. 关键字函数没有顺序之分
  1. 缺省参数
# 缺省参数又叫默认参数
def test1(name, age, gender='男'):
    print(f'你的名字{name}, 年龄{age}, 性别{gender}')

test1('TOM', 18)  # 你的名字TOM, 年龄18, 性别男
test1('ROSE', 18, gender='女') # 你的名字ROSE, 年龄18, 性别女

不定长参数

# 不定长参数又叫可变参数  返回的是元组
def test1(*args):
    print(args)

test1('TOM')  # ('TOM',)
test1('TOM', 18)  # ('TOM', 18)

关键字不定长参数

# 关键字不定长参数  返回 字典
def test1(**kwargs):
    print(kwargs)

test1() # {}
test1(name='TOM', age=18) # {'name': 'TOM', 'age': 18}

id() 的基本使用

a = 1
b = a

print(id(a))
print(id(b))

可变参数 和 不可变参数

def test1(a):
    print(a)
    print(id(a))

    a += a # 不可变数据: 200  可变数据: [11, 22, 11, 22]
    print(a)
    print(id(a))

b = 100
test1(b)

c = [11, 22]
test1(c)

函数占位符 和 函数提示文档

def add_info():
    """添加学员信息"""  # 用 help() 能够访问到 函数提示文档
    pass # 占位符 防止报错

print(help(add_info))
posted @ 2022-02-20 10:12  伴你如风  阅读(16)  评论(0编辑  收藏  举报