python 作用于的问题(超级有意思)

该代码示例展示了Python中try-except-finally语句的使用,以及如何在异常处理中操作全局变量。在try块中,尝试执行可能会引发错误的代码;如果发生错误,进入except块,其中可以更改全局变量str_ok的值;最后,无论是否发生异常,finally块的代码都会执行,再次打印str_ok的值。此示例探讨了异常处理和变量作用域的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


str_ok = 'jack'
def cs_first():
    try:
        print("111=", str_ok)
        print("222=", 4 / 0)
        # try:
        #     print("1212=", str_ok)
        #     pass
        # except:
        #     pass
        # finally:
        #     print("1414=", str_ok)
        #     pass
        # pass
    except:
        # str_ok = 'lucy'
        print("222=", str_ok)
    finally:
        # str_ok = 'uuuu'
        print("333=", str_ok)


cs_first()

总结:分步,打开finally,except里面的str_ok 变量,看看作用域 或 作用。

-------------------------------------------------------------  下面是网友给出飞分析答案

1、

解决Python报错:local variable 'xxx' referenced before assignment(引) - 菜鸡一枚 - 博客园https://www.cnblogs.com/yymn/p/11104440.html

2、

python 全局变量引用与修改 - 菜鸡一枚 - 博客园https://www.cnblogs.com/yymn/p/11299805.htmlpython 全局变量引用与修改 - yanfengt - 博客园https://www.cnblogs.com/yanfengt/p/6305542.html

3、

一个网友学习python的知识点:
https://blog.youkuaiyun.com/langb2014/category_2495401.htmlhttps://blog.youkuaiyun.com/langb2014/category_2495401.html

4、

https://www.jb51.net/article/108952.htmicon-default.png?t=L9C2https://www.jb51.net/article/108952.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值