-24 python learning the local variables and global variables

    Local variables and global variables

 

1. There is no variable indentation, global variables

name = 'jphn'

Variables defined in the subroutine, local variables

 

2.

= name ' jphn ' # global variable 


DEF A (): 
    name = ' Andy ' # local variables 
    Print ( ' A ' , name) 
A ()

operation result:

a andy

Process finished with exit code 0

 

 

3.global global variables can be modified

Is not modified before:

name = 'jphn'


def a():
    name='andy'
    print('a',name)
a()

print(name)

operation result:

a andy
jphn

Process finished with exit code 0

 

I want to modify global variables;

= name ' jphn ' 


DEF A ():
     Global name #nonlocal on a specified variable, global variable specified global 
    name = ' Andy ' 
    Print ( ' A ' , name) 
A () 

Print (name)

operation result:

a andy
andy

Process finished with exit code 0

 

 

4. Nested

= name ' Bob '                             

DEF A (): 
    name = ' red ' 
    Print (name)
     DEF B (): 
        name = ' Xiaogang ' 
        Print (name)
         DEF C (): 
            name = ' Wang ' 
            Print (name)
         Print (name) 
        C () 
    B () 
    Print (name) 
A ()

operation result:

Red 
Xiaogang 
Xiaogang 
Wang 
red 

Process finished with exit code 0

 

5. Before the references

That is a function of variables

the first:

def bar():
    print('from bar')
def foo():
    print('from foo')
    bar()
foo()

operation result:

from foo
from bar

Process finished with exit code 0

second:

def foo():
    print('from foo')
    bar()
def bar():
    print('from bar')
foo()

operation result:

from foo
from bar

Process finished with exit code 0

 

Guess you like

Origin www.cnblogs.com/liujinjing521/p/11122270.html