Python学习之旅-03-代码容器:函数

2018-06-30  本文已影响12人  b861a75d2a7d

函数

1.函数的定义
2.函数的规则
3.创建一个函数
# 0 创建一个函数
def hello():
    '''不传参数的函数'''
    print('hello,world.')

def hi(str):
    '''传入参数的函数'''
    print(str)

# 1 调用函数
hello()
#输出内容:hello,world.

hi('哈喽')
#输出内容:哈喽

4.参数

调用函数时可使用的正式参数类型:

4.1 必需参数
# 必需参数:必须以正确的顺序传入函数。调用时的数量必须和声明时的一样。
def hello(str):
    print('hello,' + str)

# 调用函数
hello('python')
#输出内容:hello,python

4.2 关键字参数
# 4.2关键字参数
def boy(age,name):
    '''打印传入的姓名和年龄'''
    print("名字: ", name)
    print("年龄: ", age)

#调用函数
boy('Jason','20')

#输出内容:
# 名字:  Jason
# 年龄:  20
4.3 默认参数
# 4.2默认函数:调用函数时,如果没有传递参数,则会使用默认参数。
def boy(name, age=30):
    '''打印传入的姓名和年龄'''
    print("名字: ", name)
    print("年龄: ", age)


# 调用函数
boy('Jason')

# 输出内容:
# 名字:  Jason
# 年龄:  30

#传入参数时,就会使用传入的参数
boy('老王',100)
# 输出内容:
# 名字:  老王
# 年龄:  100

4.4 不定长参数
# *args:以元组(tuple)的形式导入,存放所有未命名的变量参数。
# **kwargs:以字典的形式导入
def hello(*args,**kwargs):
    print(*args)
    print(**kwargs)

a = {'name':'老王'}
b = ('hello','python')
hello(a)
hello(b)
#输出内容:
# {'name': '老王'}
# ('hello', 'python')

5. 匿名函数
5.1 语法
lambda [arg1 [,arg2,.....argn]]:expression

# 0 创建一个匿名函数
hello = lambda name: 'hello,' + name
# 函数名:hello
# 参数:name
# 执行语句: 'hello,' + name

print(hello('Jason'))
#输出内容:hello,Jason

6.return语句
# return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。
def hello(str):
    '''不带return表达式'''
    print('hello,',str)

def hi(str):
    '''带return表达式'''
    return 'hi:'+str

#调用函数
hello('老王')
#输出内容:hello, 老王

print(hi('Jason'))
#输出内容:hi:Jason

7.变量作用域

Python的作用域一共有4种,分别是:

x = int(2.9)  # 内建作用域
 
g_count = 0  # 全局作用域
def outer():
    o_count = 1  # 闭包函数外的函数中
    def inner():
        i_count = 2  # 局部作用域
8.全局变量和局部变量
#name 在这里是全局变量
name = 'Jason'
def boy(name):
    info = '局部变量:',name
    # info 在这里是局部变量
    print(info)

print('全局变量:',name)
boy('老王')
#输出内容:
# 全局变量: Jason
# ('局部变量:', '老王')

9.global 和 nonlocal关键字
# global:可以在函数内修改全局变量,如果没有全局变量则会新建一个
number = 1
def func():
    global number  # global 修改number为全局变量
    print(number)

func()
#输出内容:1

# 如果要修改嵌套作用域(enclosing 作用域,外层非全局作用域)中的变量则需要 nonlocal 关键字
def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal关键字声明
        num = 'hhh'
        print(num)
    inner()
    print(num)
outer()

outer()
上一篇下一篇

猜你喜欢

热点阅读