文件python菜单在第一个选项之后返回菜单


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程序。它使用户可以选择第一个选项,然后打印菜单,然后在我希望让他们再次输入菜单选择时结束。我可以看到为什么这样做,但我无法想到一种让他们选择第二/第三/第四选项的方法。谢谢。

尝试使用循环重复您的菜单。

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()

最新更新