Python global variable Operations detail _python

Source: Internet
Author: User
Tags in python

Touch python time is not long, some knowledge points, not very solid grasp, I personally advocating no matter what things to learn, first of all must go back to the foundation to play very solid, and then go higher. Today, I encountered a global variable in Python operation, encountered a problem, so, here will be the problem, make a record, with a long mind!!!

The use of global variables in Python, in fact, is not a very sensible choice, but you still believe that existence is reasonable, is how you use; Global variables reduce commonality between modules and functions; Therefore, in future programming, you should avoid using global variables as much as possible.

Use of global variables:

Method One:

In order to facilitate the code management, the global variable is unified into a module, then the global variable is imported, and the global variable module is used in this way.
To define a global variable in a module:

Copy Code code as follows:

#global. py
Global_1 = 1
Global_2 = 2
Global_3 = ' Hello world '

Then import the global variable definition module in a module and use global variables in the new module:
Copy Code code as follows:

Import Globalvalues

Def printglobal ():
Print (Globalvalues.global_1)
Print (Globalvalues.global_3)
Globalvalues.global_2 + 1 # Modify values

if __name__ = = ' __main__ ':
Printglobal ()
Print (globalvalues.global_2)

Method Two:

Define the global variable directly in the module and use it directly in the function OK. However, when using global variables, you must identify them using the global keyword in the function:

Copy Code code as follows:

CONSTANT = 0

Def modifyglobal ():
Global CONSTANT
Print (CONSTANT)
CONSTANT + 1

if __name__ = = ' __main__ ':
Modifyglobal ()
Print (CONSTANT)

!!!, finish the lecture.

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.