python global local nonlocla

2023-11-17

What is the global keyword

In Python, global keyword allows you to modify the variable outside of the current scope. It is used to create a global variable and make changes to the variable in a local context.

Rules of global Keyword

The basic rules for global keyword in Python are:

  • When we create a variable inside a function, it is local by default.
  • When we define a variable outside of a function, it is global by default. You don’t have to use global keyword.
  • We use global keyword to read and write a global variable inside a function.
  • Use of global keyword outside a function has no effect.

Use Global

x = "global "

def foo():
    global x
    y = "local"
    x = x * 2
    print(x)
    print(y)

foo()

output

global global
local

Example 1: Accessing global Variable From Inside a Function

c = 1 # global variable

def add():
    print(c)

add()

output

1
This seems fine, however we may have some scenarios where we need to modify the global variable from inside a function.

Example 2: Modifying Global Variable From Inside the Function

c = 1 # global variable
    
def add():
    c = c + 2 # increment c by 2
    print(c)

add()

output error

UnboundLocalError: local variable ‘c’ referenced before assignment

This is because we can only access the global variable but cannot modify it from inside the function.

solution: use the ‘global’ keyword.

Example 3: Changing Global Variable From Inside a Function using global

c = 0 # global variable

def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)

add()
print("In main:", c)

output:

Inside add(): 2
In main: 2

Global in Nested Functions

Example 5: Using a Global Variable in Nested Function

def foo():
    x = 20

    def bar():
        global x
        x = 25
    
    print("Before calling bar: ", x)
    print("Calling bar now")
    bar()
    print("After calling bar: ", x)

foo()
print("x in main: ", x)

output

Before calling bar: 20
Calling bar now
After calling bar: 20
x in main: 25

In the above program, we declared a global variable inside the nested function bar(). Inside foo() function, x has no effect of the global keyword.

Before and after calling bar(), the variable x takes the value of local variable i.e x = 20. Outside of the foo() function, the variable x will take value defined in the bar() function i.e x = 25. This is because we have used global keyword in x to create global variable inside the bar() function (local scope).

If we make any changes inside the bar() function, the changes appear outside the local scope, i.e. foo().

Example of Scope and Namespace in Python

def outer_function():
    b = 20
    def inner_func():
        c = 30

a = 10

Here, the variable a is in the global namespace. Variable b is in the local namespace of outer_function() and c is in the nested local namespace of inner_function().

When we are in inner_function(), c is local to us, b is nonlocal and a is global. We can read as well as assign new values to c but can only read b and a from inner_function().

If we try to assign as a value to b, a new variable b is created in the local namespace which is different than the nonlocal b. The same thing happens when we assign a value to a.

However, if we declare a as global, all the reference and assignment go to the global a. Similarly, if we want to rebind the variable b, it must be declared as nonlocal. The following example will further clarify this.

def outer_function():
    a = 20

    def inner_function():
        a = 30
        print('a =', a)

    inner_function()
    print('a =', a)


a = 10
outer_function()
print('a =', a)

output

a = 30
a = 20
a = 10

In this program, three different variables a are defined in separate namespaces and accessed accordingly. While in the following program,

def outer_function():
    global a
    a = 20

    def inner_function():
        global a
        a = 30
        print('a =', a)

    inner_function()
    print('a =', a)


a = 10
outer_function()
print('a =', a)

output

a = 30
a = 30
a = 30

Nonlocal Variables

Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope.

Let’s see an example of how a nonlocal variable is used in Python.

We use nonlocal keywords to create nonlocal variables.

def outer():
    x = "local"

    def inner():
        nonlocal x
        x = "nonlocal"
        print("inner:", x)

    inner()
    print("outer:", x)


outer()

output

inner: nonlocal
outer: nonlocal

In the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. The inner() function is defined in the scope of another function outer().

Note : If we change the value of a nonlocal variable, the changes appear in the local variable.

Reference

  1. Programiz - Python Global, Local and Nonlocal variables
  2. Programiz - Python Global Keyword
  3. Python Namespace and Scope
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python global local nonlocla 的相关文章

随机推荐

  • 数字芯片流程

    芯片设计分为前端设计和后端设计 前端设计 逻辑设计 和后端设计 物理设计 并没有同意严格的界限 这个过程中涉及到了与工艺有关的设计就是后端设计 一 需求分析 产品需要解决的问题 预测3 5年的趋向和走势 确保前瞻性 确保芯片是有卖点的 客户
  • kong dashboard UI 的使用 (使用kong 对服务反向代理,以及解决跨域问题)

    7 2Choose Security and click on ADD PLUGIN in cors then don t input content and click on ADD PLUGIN button directly 第一步登
  • 【Zotero6】插件Zotcard自定义笔记模板流程分享

    Zotero 个人感觉比Endnote更好用的文献管理器 集翻译 文献整理 笔记 查询期刊影响因子 期刊分区等集于一身的文献管理器 据说是一款开源软件官网就可以免费下载 安装附加的浏览器插件使用更方便 今天更新的是Zotero中的笔记插件
  • 计算机操作系统pcb是什么意思,简述PCB的含义以及作用

    描述 为了使参与并发执行的每个程序 包含数据都能独立地运行 在操作系统中必须为之配置一个专门的数据结构 称为进程控制块 PCB Process Control Block 进程与PCB是一一对应的 用户进程不能修改 进程控制块PCB的作用
  • muduo 架构解析

    muduo是一个基于Reactor模式的C 网络库 它采用非阻塞I O模型 基于事件驱动和回调 我们不仅可以通过muduo来学习linux服务端多线程编程 还可以通过它来学习C 11 Reactor是网络编程的一般范式 我们这里从react
  • RockyLinux9.1环境初始化

    下载镜像 https rockylinux org download 基础设置 硬件配置 系统配置 系统初始化 配置网络 配置网络 etc NetworkManager system connections ens160 nmconnect
  • 要言不烦先行指标与滞后指标的12个要点

    先行指标 leading indicator 是在结果发生之前对结果具有预测作用的度量数据 又称为超前指标 预测性指标 先导指标 领先指标 行为指标 过程指标等 滞后指标 lagging indicator 是对最终结果的度量数据 反映的是
  • jar包读取资源文件报错:找不到资源文件(No such file or directory)

    1 遇到问题 1 Maven项目开发阶段正常运行 Java程序可以读取配置文件 public class Main public static void main String args throws Exception Main read
  • python——返回函数、闭包函数、偏函数

    文章目录 1 返回函数 2 闭包函数 3 偏函数 1 返回函数 函数的返回值也可以是函数 def food name 外函数 def prepare 内函数 print f name 制作步骤 备菜 内部函数可以使用外部函数的变量 def
  • 看涨期权计算例题(期权案例计算)

    看涨期权又称认购期权 买进期权 买方期权 买权 延买期权 或 敲进 是指期权的购买者拥有在期权合约有效期内按执行价格买进一定数量标的物的权利 下文为大家科普看涨期权计算例题 期权案例计算 本文来自 期权酱 当看涨期权 Call Option
  • 同步资源失败,未得到同步资源的授权,请停止运行后重新运行,并注意手机上的授权提示

    问题描述 提示 HBuilderX 真机调试异常 这个问题困惑了我好几天 终于解决了 同步资源失败 未得到同步资源的授权 请停止运行后重新运行 并注意手机上的授权提示 解决方案 提示 使用adb删除对应包名 问题未解决 尝试重新启动手机再运
  • 第十届蓝桥杯省赛C++B组 数列求值

    试题 C 数列求值 本题总分 10 分 问题描述 给定数列 1 1 1 3 5 9 17 从第 4 项开始 每项都是前 3 项的和 求第 20190324 项的最后 4 位数字 答案提交 这是一道结果填空的题 你只需要算出结果后提交即可 本
  • 以数据为中心的标记语言-->yaml

    目录 一 yaml 介绍 二 yaml 基本语法 三 数据类型 1 字面量 2 对象 3 数组 四 yaml 应用实例 1 需求 2 需求图解 3 代码实现 五 yaml 使用细节 一 yaml 介绍 YAML 是 YAML Ain t a
  • C++ 之 explicit,mutable,volatile 浅析

    explicit 放在构造函数前面可以阻止构造函数的隐式类型转换 这样可以避免不必要的错误 代码用例 public static explicit operator RMB float f uint yuan uint f uint jia
  • STM32 ADC详解

    目录 01 ADC简介 02 STM32的ADC外设 03 STM32ADC框图讲解 04 触发源 05 转换周期 06 数据寄存器 07 中断 08 电压转换 09 电路图设计 10 代码设计 01 ADC简介 ADC是Analog to
  • 给Linux扩充swap分区

    https blog csdn net u011109881 article details 73694700
  • 【计算机视觉

    文章目录 一 检测相关 1篇 1 1 SegmentAnything helps microscopy images based automatic and quantitative organoid detection and analy
  • vue-cli3项目打包后自动化部署到服务器

    一 安装 scp2 npm install scp2 save dev 二 写好脚本 例如 upload js 下面任选一个即可 位置和 package json平级即可 简略版 use strict 引入scp2 var client r
  • ctfhub 基础认证

    1 打开题目环境 2 点击click跳出来一个登录弹窗 随便输入用户名和密码登录试试 没有返回任何有用信息 3 查看附件 得到一堆密码 应该是要直接爆破 4 点击click抓包后发送到repeater模块 重新发包得到 Do u know
  • python global local nonlocla

    目录 What is the global keyword Rules of global Keyword Use Global Example 1 Accessing global Variable From Inside a Funct