一、画图题
"""
下述所有代码画图以及分析代码执行流程:
1、以定义阶段为准,先画出名称空间的嵌套关系图
2、然后找到调用函数的位置,写出函数调用时代码的执行过程,涉及到名字的查找时,参照1中画好的嵌套图,标明查找顺序,一层一层直到找到位置
"""
1、题目一
input = 333 # 2
def func(): # func 3
input = 444
func()
print(input) # print 4
2、题目二
def func():
print(x)
x = 111
func()
3、题目三
x = 1
def func():
print(x)
def foo():
x = 222
func()
foo()
4、题目四
input = 111
def f1():
def f2():
# input=333
print(input)
input = 222
f2()
f1()
5、题目五
x = 111
def func():
print(x) #
x = 222
func()
6、题目六
x = 111
def foo():
print(x, )
def bar():
print(x)
foo()
bar()
7、题目七
x = 1
def func2():
func1()
x = 2
def func1():
print(x)
x = 3
func2()
二、操作题:
1、如下全局变量记录了当前登录用户,编写登录功能,一旦用户登录成功,则将全局变量赋值为当前登录的用户名
login_user = None
username, password = 'egon', '123'
# 在全局中直接修改
"""
name = input('输入用户名>>:').strip()
pwd = input('输入用户密码>>:').strip()
if username == name and pwd == password:
login_user = name
print(f"登录成功【{name}】")
else:
print('登录失败')
print('login_user:', login_user)
"""
# 在函数中使用global修改
def login():
name = input('输入用户名>>:').strip()
pwd = input('输入用户密码>>:').strip()
if username == name and pwd == password:
global login_user
login_user = name
print("登录成功")
return login_user
else:
print('登录失败')
# print(login())
print('login_user:', login_user)
# 在嵌套函数中使用nonlocal修改
def wrapper():
login_user = None
def login():
name = input('输入用户名>>:').strip()
pwd = input('输入用户密码>>:').strip()
if username == name and pwd == password:
global login_user
login_user = name
print(f"登录成功【{name}】")
return login_user
else:
print('登录失败')
login()
print('login_user:', login_user)
# wrapper()
2、针对之前编写的查询余额的功能,添加额外的逻辑:如果用户没有登录,则先执行登录功能
"""
现在当前目录下创建db.txt文件,文件内容如下:
egon:123:222
alex:123:999
"""
DB_PATH = r'db.txt'
login_state = set()
def login(name, pwd):
with open(DB_PATH, mode='rt', encoding='utf-8') as f:
for line in f:
res = line.strip()
if not res:
continue
username, password, balance = res.split(":")
if username == name and password == pwd:
print(f"登录成功【{name}】")
login_state.add(username)
return True
else:
print('登录失败')
def check_banlance():
while True:
name = input('输入用户名>>:').strip()
if name.lower() == 'q':
break
if name not in login_state:
print("请先登录")
pwd = input('输入用户密码>>:').strip()
flag = login(name, pwd)
if not flag:
continue
else:
print('欢迎再次登录。。。。')
with open(DB_PATH, mode='rt', encoding='utf-8') as f:
for line in f:
res = line.strip()
if not res:
continue
username, password, balance = res.split(":")
if username == name:
print(f'您当前余额:【{balance}】元'.center(50, '-'))
break
# check_banlance()