马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 深山小兽 于 2020-10-28 09:10 编辑
函数1里的red_choose怎么弄才能在函数2,3互通使用。下面代码有错误,无法互通。每次执行 都在句子1卡住。
def user_choose():
global i
global num_dict
print("欢迎进入自选号码菜单!\n")
print("如果想返回上级菜单请输入R!")
red_list_choose = []
blue_list_choose = []
j = 0
def isdigited(red_choose,scoped): # 函数1
nonlocal j
nonlocal red_list_choose
nonlocal blue_list_choose
if red_choose.isdigit():
red_choose = int(red_choose)
red_list_choose.append(red_choose)
scoped()
def red_scoped(): # 函数2
nonlocal j
nonlocal red_choose
nonlocal red_list_choose
nonlocal blue_list_choose
if red_choose not in range(1, 33):
red_list_choose.pop()
red_choose_s = input("您输入的红球超出范围,请重新输入!") # 句子1
isdigited(red_choose_s, red_scoped)
def blue_scoped(): # 函数3
nonlocal j
nonlocal blue_choose
nonlocal red_list_choose
nonlocal blue_list_choose
if blue_choose not in range(1, 17):
blue_list_choose.pop()
blue_choose = input("您输入的号码超出范围,请重新输入!")
isdigited(blue_choose, blue_scoped)
while True:
red_choose = input("请您选择红色号码,请在1到32之间选择:")
isdigited(red_choose, red_scoped)
while red_list_choose.count(red_choose) == 2:
red_list_choose.pop()
red_choose = input("您输入的号码之前已经存在,号码重复,请重新输入:")
isdigited(red_choose, red_scoped)
if len(red_list_choose) == 5:
while True:
blue_choose = input("您已经选择五个红色号码,请在1到16之间选择蓝球:")
isdigited(blue_choose, blue_scoped)
while blue_list_choose.count(blue_choose) == 2:
blue_list_choose.pop()
blue_choose = input("您输入的蓝球号码重复,请重新输入:")
isdigited(blue_choose, blue_scoped)
blue_list_choose.append(blue_choose)
if len(blue_list_choose) == 2:
i += 1
j += 1
# 复习列表推导式 red_list_choose_d = ["%-2d" % x for x in red_list_choose]
# 复习列表推导式 blue_list_choose_d = ["%-2d" % y for y in blue_list_choose]
str_red = []
str_blue = []
for each in red_list_choose: # 格式化红球
each = str(each)
if len(each) == 1:
each = '0' + each
str_red.append(each)
for each in blue_list_choose: # 格式化蓝球
each = str(each)
if len(each) == 1:
each = '0' + each
str_blue.append(each)
num_dict[i] = "红球是: ", red_list_choose, "蓝球是: ", blue_list_choose
red_list_choose = []
blue_list_choose = []
print("您已经自选了%-2d组号码,请自选您的第%-2d组号码!" % (j, j + 1))
break
if blue_choose in ["r", "R"]:
main()
if red_choose in ["r", "R"]:
main()
user_choose()
加个参数就可以了。调用的时候给出flag,需要判断红球的时候这个参数flag给成True,需要判断蓝球的时候给成False。其实你的函数2和函数3也可以这样写。代码复用,才是编程精髓 def isdigited(flag,scoped): # 函数1
nonlocal j
nonlocal red_list_choose
nonlocal blue_list_choose
nonlocal red_choose
nonlocal blue_choose
if flag:#flag为True的时候是针对红球的,否则是针对蓝球的
if red_choose.isdigit():
red_list_choose.append(red_choose)
scoped()
else:
if blue_choose.isdigit():
blue_list_choose.append(blue_choose)
scoped()
|