10. Function two

Function two

1. Function return value

return:可返回运算结果,并退出函数
break:跳出当前循环
continue:跳过本次循环,进入下一次循环
def fn1():
    def fn2():
        print("这是fn2")
    return fn2
fn1()()
显示结果:这是fn2

Summary: Here return returns the fn2 object, so after calling fn1, call it again to display the contents of fn2

在这里插入代码片

2. Documentation string

文档注释,用三引号表示
help(函数对象) 显示帮助文档

3. The scope of the function

global 全局变量   
函数内部的变量可以改变全局变量的值
global置于函数内部

4. Namespace

locals 显示当局变量,以字典形式出现
globals 显示全局的变量,以字典形式出现
def fn(b):
    c=2
    print(f'locals显示为{locals()}')
    print(f'globals显示为{globals()}')
    if len(b)==1 or len(b)==0:
        return True
    elif b[0]==b[-1]:
        return fn(b[1:-1])
    else:
        return False
fn('a')
显示结果为:
locals显示为{'c': 2, 'b': 'a'}
globals显示为{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000018DDF7BB358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/PycharmProjects/v3/20191018.py', '__cached__': None, 'fn': <function fn at 0x0000018DDF6B1E18>}

Conclusion: The display results are different, locals shows the variables in the def function,
globals is shown as variables in the global

5. Recursive function

递归式函数有两个条件
1.基线条件
问题可以被分解为最小的问题,当满足基线条件的时候,递归就不在执行了
2.递归条件
将问题可以分解的条件

练习:用来检测任意字符串是否是回文字符串,如果是返回True,如果不是返回False
def fn(b):
    if len(b)==1 or len(b)==0:
        return True
    elif b[0]==b[-1]:
        return fn(b[1:-1])
    else:
        return False
print(fn('abcba'))

Display result: True

Guess you like

Origin blog.csdn.net/qq_37697566/article/details/102626381