Namespace and scope of learning python

Operational requirements: The following drawing all the code and analysis code execution flow
1, subject to the definition phase, the first nesting relationship shown in FIG namespace
2, and then locate the calling function, execution of function calls to write the code, when it comes to find the name, referring to a good 1-in-picture
nested chart, indicating the search order, layer by layer until you find the location

=================== =================== a topic

input=333
def func():
    input=444
func()
print(input)   #333

Program code execution process:

Execute code func ():

1) func () is the local name space has a name input bound memory address 444

Execute code print (input):

2) found in the present input layer name space (global name space) = 333, 333 so printing

=================== title two ===================

def func():
    print(x)
x=111

func()   #111

Execute code func ():

① x first look in a local variable space layer of the present function func found no;

② then up one global name space to find x, find x = 111, 111 and therefore Print

=================== title three ===================

x=1
def func():
   print(x)

def foo():
    x=222
    func()

foo()    #1

During the definition phase of the first function, except in the function func function foo the call, rather than defining, and therefore the function func local namespace local name space and function foo are completely independent of each other parallel to the cut, there is no 'nested' relations, their upper namespace is the global namespace.

Code execution foo:

1) execution code x = 222, 222 bind to the memory address x;

2) execution code func (),

① first looks in the local namespace x in func, and func in the local name space is not x;

② up one global name space to find x, find x = 1, and therefore print 1.

=================== title four ===================

input=111
def f1():
    def f2():
        # input=333
        print(input)
    input=222

    f2()

f1()   #222

Execute code f1 ():

① first performs input = 222, 222 bind to the memory address INPUT;

② then perform f2 (), need to print x, first look in the local name space input function f2, we found no;

③ Then a layer up local namespace lookup function f1 of input, find the input = 222, print 222.

=================== title five ===================

x=111
def func():
    print(x) #
    x=222

func()        #UnboundLocalError: local variable 'x' referenced before assignment

Execute code func ():

Print first execution code (x), x need to print, to find x in the function func local namespace of the present layer, this layer is found promising x defined, but to x is defined before the printing is x, an error is reported: referenced in the local variable x are as defined before.

=================== title six ===================

x=111

def foo():
    print(x,)

def bar():
    print(x)

foo()        #111
bar()        #111

1) execution code foo ()

Print execution code ① (x,), the local name space to find x in this layer function foo, is not found;

② towards top global name space to find x, find x = 111, print 111.

2) execution of the code bar ()

Process and content 1) of the same.

=================== title seven ===================

x=1
def func2():
    func1()

x=2
def func1():
    print(x)

x=3

func2()            #3

Execution code func2 ()

① call the function func1 ()

② execution code PINT (x), x need to print; x Looking at the present level function func1 () of the local name space is not found;

③ To find the global namespace upper x, find x = 3, the output 3.

=================== title eight ===================
1, the following global variables records the current logged-on user , writing a login function, once the user logs in successfully, then the global variable assignment for the current logged-on user name login_user = None

def log_in():
    global login_user
    while True:
        inp_name = input('请输入你的账号:').strip()
        user_info = {}
        with open('db.txt','rt',encoding='utf-8') as f:
            for line in f:
                user_name,pwd = line.strip().split(':')
                user_info[user_name] = pwd
        if inp_name in user_info:
            inp_pwd = input('请输入你的密码:').strip()
            if inp_pwd == user_info[inp_name]:
                print('登录成功。')
                login_user = inp_name
                break
            else:
                print('密码错误,登录失败。')
        else:
            print('你输入的账号不存在,请重新输入。')

2, for the balance of the query written before the function, add additional logic: if the user is not logged in, log in to perform the function

def check_balance():
    while True:
        inp_name = input('请输入你的账号:').strip()
        user_balances = {}
        with open('user_balance.txt','rt',encoding='utf8') as f:
            for line in f:
                user_name,balance = line.strip().split(':')
                user_balances[user_name] = balance
        if inp_name in user_balances:
            if inp_name == login_user:
                print('用户 {} 的余额为: {} 元。'.format(inp_name,user_balances[inp_name]))
                break
            else:
                print('你还没有登录,请登录后再进行查询。')
                log_in()
        else:
            print('你输入的账号不存在,请重新输入。')

login_user = None
check_balance()

Guess you like

Origin www.cnblogs.com/leilijian/p/12526784.html