Get the App
SLTechnology News&Howtos  ›  Development  › 

Description and usage of nonlocal keyword in python

Shulou Source: shulou.com Published: 2022-06-03 17:30:53 09月23日 Update

This article mainly explains the "explanation and use of the nonlocal keyword in python". The content of the explanation in 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 "the explanation and usage of the nonlocal keyword in python".

Description

1. The variables declared by nonlocal are not local or global variables, but variables in external nested functions.

2. The variables defined by nonlocal will only play a role in the called subfunctions.

Example

X = 1def func (): nonlocal x x = 2 print (x) func () print (x) result code error, SyntaxError: no binding for nonlocal'x 'found

Why did I just change global to nonlocal and report it wrong? Because nonlocal is a function used in a function.

X = 1def func (): X = 2 def subfunc (): nonlocal x x = x + 1 print ('value printed within subfunc:% d'% x) return x print (value printed in 'func:% d'% x) return subfuncfunc () print (value printed outside func:% d'% x) the result is: value printed within func: value printed outside 2func: 1

The nonlocal keyword does not change the value of either the global variable xroom1 or the local variable xroom2. This means that the variables declared by nonlocal are not local or global variables.

Thank you for reading, the above is the content of "the description and usage of the nonlocal keyword in python". After the study of this article, I believe you have a deeper understanding of the description and use of the nonlocal keyword in python, 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 keywords keywords usage methods functions global local learning content that is results code functions just examples ideas situations articles more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker macOS OPPO Reno Shulou Technology MariaDB