Comparison between global and nonlocal in Python

Source: Internet
Author: User
The order in which Python references variables: current scope local variables, outer scope variables, global variables in current module->python built-in variables

First, global

The global keyword is used to use globals in functions or other local scopes. However, if you do not modify global variables, you can not use the Global keyword.

Copy the Code code as follows:


Gcount = 0

Def global_test ():
Print (Gcount)

Def global_counter ():
Global Gcount
Gcount +=1
Return Gcount

Def global_counter_test ():
Print (Global_counter ())
Print (Global_counter ())
Print (Global_counter ())

Second, nonlocal

The nonlocal keyword is used to use an outer (non-global) variable in a function or other scope.

Copy the Code code as follows:


Def make_counter ():
Count = 0
Def counter ():
nonlocal count
Count + = 1
return count
Return counter

Def make_counter_test ():
MC = Make_counter ()
Print (MC ())
Print (MC ())
Print (MC ())

You can also use generator to implement similar counter. As follows:

Copy the Code code as follows:


Def counter_generator ():
Count = 0
While True:
Count + = 1
Yield count

Def counter_generator_test ():
# below is for Python 3.x and works well
Citer = Counter_generator (). __iter__ ()
i = 0
while (I < 3):
Print (citer.__next__ ())
I+=1

Def counter_generator_test2 ():
#below code don ' t work
#because Next () function still suspends and cannot exit
#it seems the iterator is generated every time.
j = 0
For ITER in Counter_generator ():
while (J < 3):
Print (ITER)
J+=1
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.