Python global variables and local variables related knowledge points

Source: Internet
Author: User

#知识点一:

#在函数外面定义的变量叫全局变量
num = 100

Def AAA ():
  ‘‘‘
If you modify the global variable directly in the function, an exception is generated
If you really need to modify it, you can declare it in the function (add global above)
‘‘‘
Global num
Print (num)
num+=2
Print (num)

Def BBB ():
Print (num)

AAA () #输出100和102
The value of the global variable num after #调用函数AAA () really changed.
BBB () #输出102


#知识点二:
‘‘‘
If the global variable is a mutable type, such as a list or dictionary, it can be modified directly in the function;
For an immutable type, such as int, it cannot be modified directly in the function.
‘‘‘
Nums = [11,22,33]
info = {"Name": "Xiaowang", "Age": 24}

def test ():
Print ("-" *20)
  # nums.append (#列表可以在函数中修改)
# Print (nums)
info[' name '] = ' Xiaoli '
Print (info)

Def test2 ():
Print ("=" *20)
  # Print (nums)
Print (info)

Test ()
Test2 ()
#上述两次打印结果一样


#知识点三:
#为了防止和局部变量名字相同, so add a G before the global variable
# g_a = 200
A = 200

def test3 ():
Print ("-" *20)
  #a +=1 #这种情况下是直接修改a的值, but because a outside the function is a global variable cannot be modified within a function, an error will be

A = 100
  ‘‘‘
Note One: Here it is possible to redefine a new variable A, and it is possible to modify the value of a, but because the global
Variable A cannot be modified, so here is a redefinition of A;
Note two: If a local variable has the same name as the global variable, the local variable is used
‘‘‘
Print (a)

Def test4 ():
Print ("=" *20)
Print (a)
  #print (b) # name ' B ' is not defined
  #变量的使用顺序是: global variable, local variable, if neither, the program will error

Test3 () #打印100
Test4 () #打印200

Python global variables and local variables related knowledge points

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.