Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Description and usage of nonlocal keyword in python

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report