Python--函数

# 函数/方法/功能
# 说白了,函数就是把一堆代码组合到一起变成一个整体
# 函数不调用不会被执行
# 提高代码的复用性

# 全局变量/局部变量
# 位置参数/必填参数


# def hello(file_name, content=''): # 这里的参数叫做形参,形式参数
# # 函数里面变量是局部变量
# f = open(file_name, 'a+', encoding='utf-8')
# if content:
# f.write(content)
# res = ''
# else:
# f.seek(0)
# res = f.read()
# f.close()
# return res # 返回值


# 如果想获取函数的结果,那么必须return
# 如果函数没有写return的话,返回值是None,return不是必须写的
# return立即结束函数

# users = hello('wangsilei.txt') # 实参,实际参数
# print(users)
# wsl = hello('wangsilei1.txt', '你好panda')
# print(wsl)


# 默认值参数/不是必填的
# def hello_world(name='panda_boy!'):
# print(name)
#
#
# hello_world()
# hello_world('wangsilei')

a = 100 # 全局变量


def test():
global a # 声明全局变量
a = 5
print('里面的', a)


test()
print('外面的', a)

# 可变参数


# def test(a, b=1, *args): # 可变参数
# print('a', a)
# print('b', b)
# print('args', args)
# # print(args[0])
#
#
# test('haha', 2, '123', '456', '789') # 位置调用
# test(b=5, a=10) # 关键字调用
#
# t = [1, 2, 3]
# test(*t)

# 关键字参数
def test2(a=1, **kwargs):
print(a)
print(kwargs)


test2()
test2(a=2, name='haha', sex='nv')
原文地址:https://www.cnblogs.com/wangsilei/p/8251338.html