函数的对象
一、函数对象的四大功能
函数是第一类对象,即函数可以被当作数据处理
def func():
print('from func')
print(func)
<function func at 0x10af72f28>
1、引用
x = 'hello nick'
y = x
f = func
print(f)
<function func at 0x10af72f28>
2、当作参数传给一个函数
len(x)
def foo(m):
m()
foo(func)
from func
3、可以当作函数的返回值
def foo(x):
return x
res = foo(func)
print(res)
res()
<function func at 0x10af72f28>
from func
4、可以当作容器类型的元素
l = [x]
function_list = [func]
function_list[0]()
from func
二、猜年龄游戏
import random
def register():
print('欢迎来到注册页面')
username = input('请输入你的用户名:')
pwd = input('请输入你的密码')
with open('userinfo.txt', 'a', encoding='utf8') as fa:
fa.write(f'{username}:{pwd}|')
def login():
print('欢迎来到登录页面')
username = input('请输入你的用户名:')
pwd = input('请输入你的密码')
with open('userinfo.txt', 'r', encoding='utf8') as fr:
data = fr.read()
data_split = data.split('|') # ['nick:123','tank:123']
userinfo = f'{username}:{pwd}'
if userinfo in data_split:
print('登录成功')
else:
print('登录失败')
def get_price_dict():
"""获取奖品字典"""
with open('price.txt', 'r', encoding='utf8') as f: # price.txt右下角为什么编码,则encoding为什么编码
price_dict = f.read()
price_dict = eval(price_dict) # type:dict # 获取奖品字典
return price_dict
def select_price(price_dict):
"""选择奖品"""
price_self = dict()
# 打印商品
for k, v in price_dict.items():
print(f'奖品编号:{k} {v}')
# 获取奖品的两次循环
for i in range(2):
price_choice = input('请输入你需要的奖品编号:')
if not price_choice.isdigit():
print("恭喜你已经获得一次奖品,奖品为空!并且请输入正确的奖品编号!")
continue
price_choice = int(price_choice)
if price_choice not in price_dict:
print('你想多了吧!')
else:
price_get = price_dict[price_choice]
print(f'恭喜中奖:{price_get}')
if price_self.get(price_get):
price_self[price_get] += 1
else:
price_self[price_get] = 1
print(f'恭喜你获得以下奖品:{price_self}')
def guess_age():
"""猜年龄函数"""
print("欢迎来到猜年龄游戏")
age = random.randint(18, 60) # 随机一个数字,18-60岁
count = 0 # 计数
while count < 3:
count += 1
inp_age = input('请输入你想要猜的年龄:')
# 判断是否为纯数字
if not inp_age.isdigit():
print('搞事就骂你傻逼')
continue
inp_age = int(inp_age)
# 筛选年龄范围
if inp_age > 60 or inp_age < 18:
print('好好题目,18-60岁,非诚勿扰')
continue
# 核心逻辑
if age == inp_age:
print('猜中了,请选择你的奖品')
price_dict = get_price_dict()
select_price(price_dict)
break
elif age > inp_age:
print('猜小了')
elif age < inp_age:
print('猜大了')
continue
msg = '''
1: 登录
2: 注册
3: 猜年龄游戏
'''
func_dic = {
'1': login,
'2': register,
'3': guess_age,
}
print(msg)
choice = input('请选择你需要的功能:')
func_dic[choice]()

浙公网安备 33010602011771号