我想要一个程序,从主菜单开始,分支到不同的功能。在每个功能结束时,我希望用户被问到“你想回到主菜单吗?”如果用户说不,我希望程序通过停止主循环来终止(我不想使用系统出口()或任何类似的东西)。 示例代码:
#Issue is almost at the bottom
#Feel free to comment on the rest of the code as well,
#Always looking to improve
def main():
loop = True
while loop:
print('''MENU CHOICE''')
print('''1: go here''')
print('''2: go there''')
print('''3: You get the point''')
print('''0: Terminate program''')
print()
try:
answer = int(input('''I want to go to program: '''))
except:
print('''Not a valid menu choice, please try again''')
print()
if answer != 1 and answer != 2 and answer != 3 and answer != 0:
print('''Not a valid menu choice, please try again''')
print()
elif answer == 1:
program1()
elif answer == 2:
program2()
elif answer == 3:
program3()
else:
loop = False
def program1():
print('''This is program 1''')
itdontwork = input('''Do you want to go back to the menu? Y/N''')
if itdontwork == 'Y' or itdontwork == 'y':
print()
else:
print('''SHUTTING DOWN''')
loop = False #Here is the issue
#The rest of the programs would be the same
main()
最简单的方法是使变量循环全局化
Global将允许您在任何地方都有相同的w/r变量。没有全局变量,所有变量都是局部变量。在
问题是您试图更改在
program1
函数范围之外定义的变量。loop
是在main
中定义的,因此只有main
可以访问它。有几种方法可以解决这个问题,您可以在外部声明loop
(使其成为一个全局的),或者让您的program1
向调用函数返回一个布尔值,例如:我想你想做的是让不同的程序返回一个值。在
问题是函数被执行但什么也不返回。你的main函数什么也不返回;因此循环变量永远不能被更新来中断循环。在
相关问题 更多 >
编程相关推荐