day11-函数、可变长参数、名称空间和作用域
函数的定义
函数的三种定义方式
空函数
有参函数
无参函数
函数的返回值
函数的调用
函数的参数
形参
位置形参
默认形参
实参
位置实参
关键字实参
可变长参数
*形参
接收多余的位置实参
**形参
接收多余的关键字实参
*实参
把列表打散成位置实参
**实参
把字典打散成关键字实参
*形参**形参
接收所有的多余的参数
函数对象
1、引用
2、作为容器类元素
3、作为函数参数
4、作为函数的返回值
函数嵌套
def func1():
print('func1')
def func2():
print('func2')
#不能在外部调用内层函数
名称空间和作用域
内置名称空间
放内置方法
全局名称空间
除了内置和局部就是全局
局部名称空间
函数内部定义的变量/函数
执行顺序
内置->全局->局部
搜索顺序
(从当前位置开始)局部->全局->内置
全局作用域
全局作用域和局部作用域的变量没有关系,可变数据类型除外
局部作用域
局部作用域之间的变量没有关系
global
局部的可以修改全局的
nonlocal
局部的可以修改外层局部的
LEGB原则
购物车默写
def read_info(name):
with open('user_info.txt','r',encoding='utf_8')as fr:
for line in fr:
line = line.strip()
lis = line.split(':')
if lis[0] == name:
return lis
def write_info(name_w, pwd_w):
with open('user_info.txt','a',encoding='utf_8')as fw:
fw.write(f'{name_w}:{pwd_w}\n')
def login():
print('欢迎客官登陆')
if user_session:
print('您已登陆!')
return
count = 0
while count < 3:
name_l = input('请客官留下姓名: ').strip()
pwd_l = input('请客官输入密码: ').strip()
lis = read_info(name_l)
if not lis:
print('对不起客官还没有注册哦')
return
if pwd_l == lis[1]:
user_session.append(name_l)
print('登陆成功')
return
def register():
print('欢迎客官来注册')
count = 0
while count < 3:
name_r = input('请客官留下姓名: ').strip()
pwd_r = input('请客官输入密码: ').strip()
re_pwd = input('烦请客官再次输入密码: ').strip()
if pwd_r != re_pwd:
print('两次密码不一样哦')
count += 1
continue
write_info(name_r, pwd_r)
print('注册成功!')
break
def logout():
if not user_session:
print('请客官先登陆哦')
return
print('注销成功!')
user_session.clear()
def shopping():
if not user_session:
print('请客官先登陆哦')
return
while True:
print('''
1 AD钙奶
2 旺仔牛奶
3 dog shit
q 结束购买
''')
goods_choice = input('请客官选购: ').strip()
if goods_choice == 'q':
break
if goods_choice in shopping_car_dict:
shopping_car_dict[goods_dict[goods_choice]] += 1
else:
shopping_car_dict[goods_dict[goods_choice]] = 1
print(shopping_car_dict)
def shopping_car():
if not user_session:
print('请客官先登陆哦')
return
print('欢迎来到购物车功能!')
shopping_car_dict.clear()
goods_dict = {
'1':'AD钙奶',
'2':'旺仔牛奶',
'3':'dog shit'
}
shopping_car_dict = {}
func_dict = {
'1':login,
'2':register,
'3':logout,
'4':shopping,
'5':shopping_car
}
user_session = []
while True:
print('''
1 登陆
2 注册
3 注销
4 购物
5 购物车
q 退出
''')
choice = input('请输入选择: ').strip()
if choice == 'q':
break
if choice in func_dict:
func_dict[choice]()
else:
print('臭傻逼,打数字!')
浙公网安备 33010602011771号