欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python 全局变量与局部变量、函数递归

程序员文章站 2023-12-21 20:47:28
...
局部变量 全局变量

x = 3
y = 2 * x + 1

print(y)

name = 'sss'


def change_name():
    global name  # 修改全局变量
    name = '帅'

    print('change_name', name)


change_name()

print(name)

变量私有化只能是函数

name = 'kkk'


def change_name():
    name1 = '帅'
    name2 = '酷'
    name3 = '美'

    print('change_name', name1)


change_name()

print(name)

_global

name = 'ski'


def ssdf():
    global name
    name = '帅'
    print('sdd', name)


def qio():
    print('sdd', name)


qio()
ssdf()

如果函数内 无global关键字 优先读取局部变量,无局部变量读取全局变量,
不能重新赋值  对于可变对象可以进行内不元素进行操作
如果函数中有global关键字  可以读取或者重新给全局变量赋值

name = ['sdsd', 'sbsb']


def usus():
    # global name
    # name = 'sda'
    name.append('sdwwww')
    print('局部变量', name)

usus()

print(name)

全局变量全部大写,局部变量一律小写

NAME = 'OIU'

def oness():
    name = 'poi'
    print(name)
    def twos():
        name = 'lu'
        print(name)
        def threes():
            name = 'iss'
            print(name)
        print(name)
        threes()
    twos()
    print(name)

oness()

name = 'one'


def oness():
    name = 'on1'

    def twoss():
        global name
        name = 'two'

    twoss()
    print(name)


print(name)
oness()
print(name)

name = 'one'


def oness():
    name = 'on1'

    def twoss():
        nonlocal name   #修改上一级  变量
        name = 'two'

    twoss()
    print(name)


print(name)
oness()
print(name)

风湿理论之函数即变量

def foo():
    print('from foo')
    bar()

foo()

def bar():
    print('from bar')
def foo():
    bar()
    print('from foo')

def foo():
    print('from foo')
    bar()

def bar():
    print('from bar')

foo()

风湿理论
函数即变量

name = '海风'


def huanwei():
    name = '黄伟'
    print(name)

    def liuyang():
        name = '刘洋'
        print(name)

        def nulige():
            name = '胡志华'
            print(name)

        print(name)
        nulige()

    liuyang()
    print(name)


print(name)
huanwei()
print(name)

函数递归  占用内存

def calc(n):
    print(n)
    calc(n)

calc(10)


一定要有一个指定的结束条件
没进入一层递归是,应该比上一次规模减少
递归效率不高  递归次数太多会导致栈的溢出

def calc(n):
    print(n)
    if int(n / 2) == 0:
        return n
    return calc(int(n / 2))


calc(10)


person_list = ['alex', 'wupeiqi', 'yuanhao', 'linhaifeng']


def ask_way(person_list):
    if len(person_list) == 0:
        return '没人知道'
    person = person_list.pop(0)
    if person == 'linhaifeng':
        return '找到地址'
    print('继续问下一个')
    res = ask_way(person_list)
    return res


way = ask_way(person_list)
print(way)

上一篇:

下一篇: