Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the Python keywords global and nonlocal

Shulou Source: shulou.com Published: 2022-06-01 06:59:39 10月01日 Update

This article mainly explains "how to use the Python keyword global and nonlocal". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use the Python keyword global and nonlocal".

Python keywords global and nonlocalglobaldef test (): if x is not defined in the # 1 function, x defaults to the global variable print (x) # output global v # 2. If x is defined in the function, x is the local variable x = 'local v' # local variable print (x) # output local vx = "global v" # global variable

How to modify a global variable within a function? [using keyword global]

Def test (): # declare global variables in the function first, global x # that is, x = "global v". Note that global modifies variables can not be assigned directly, such as global x = 'abc' error! # modify the global variable x = 'modified global v'x = "global v" # global variable print (x) # global vtest () print (x) # modified global vnonloacl

Nonlocal can only be used in a nested function to identify that a variable in a nested function is a variable of the same name in the function that contains the nested function. Modifying a variable in a nested function will affect the variable in the function.

Def func (): # function x = 'loval v' def ifunc (): # nested function nonlocal x # x = 'loval v'

If you modify a variable with global in a function, an error occurs when you modify a variable with the same name with nonlocal in a nested function, because nonlocal indicates that the variable has been defined in the function, but there is no local variable with the same name because the variable with the same name is modified as a global variable by global, resulting in an error

X = 'global v' # global variable def func (): # function global x def ifunc (): # nested function nonlocal x # error! Thank you for reading, the above is the content of "how to use the Python keyword global and nonlocal". After the study of this article, I believe you have a deeper understanding of how to use the Python keyword global and nonlocal, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Variables functions global key keyword local learning content output use that is ideas situations articles more identification knowledge knowledge points articles follow Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Huawei OPPO Reno NVidia Apple