def menu():
print('Choose number to continue: ')
print('1 to create file')
print('2 to read file')
print('3 to append to file')
print('4 to calculate')
print('5 to quit')
def choice():
choice=int(input('Enter menu choice: '))
return choice
def option1():
filename=input('Enter file name: ')
file=open(filename,'w')
print('Enter integers to be written to file and press enter when done.')
count=1
fox=1
while count>=1:
filedata=str(input('Enter integer '+str(fox)+' : '))
count+=1
fox+=1
file.write(filedata)
if filedata=='':
file.close()
menu
break
def option2():
try:
open(file,'r')
for line in file.readlines():
print(line)
file.close()
menu()
except:
print('Error. You must first create a file in order to read it.')
def option3():
try:
open(file,'a')
print('Enter integers to be appended to file and press enter when done.')
count=1
while count>=1:
appenddata=int(input('Enter integer to append: '))
count+=1
file.write(appenddata)
if appendata=='':
file.close()
menu
except:
print('Error. You must first create a file in order to read it.')
def option4():
file= open('file', 'r')
s = file.readlines()
p = str(s)
for line in s:
printnum = 0
total=0
printnum += int(line)
total += printnum
print("The sum is: ", total)
menu()
def option5():
quit
def main():
menu()
t=choice()
if t==1:
option1()
menu()
elif t==2:
option2()
menu
elif t==3:
option3()
menu()
elif t==4:
option4()
menu()
else:
option5()
main()
对于冗长的代码感到抱歉,这是我正在制作的菜单驱动的python程序。 它允许用户选择第一个选项,然后打印菜单然后结束,而我希望它再次输入菜单选项。我可以看到为什么它正在这样做,但我想不出一种让他们选择第二/第三/第四选项的方法。感谢。
答案 0 :(得分:0)
尝试使用循环重复菜单。
def main():
menu()
t=choice()
while t != 5:
if t==1:
option1()
elif t==2:
option2()
elif t==3:
option3()
elif t==4:
option4()
else:
print('Invalid Choice')
print('')
menu()
t=choice()
# main
main()