【问题标题】:file python menu going back to menu after first option文件python菜单在第一个选项后返回菜单
【发布时间】:2018-02-23 00:20:50
【问题描述】:
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 程序。 它让用户选择第一个选项,然后打印菜单,然后在我希望它让他们再次输入菜单选项时结束。我可以看到 为什么 这样做,但我想不出一种方法让他们选择第二/第三/第四选项。谢谢。

【问题讨论】:

    标签: python file menu


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-15
      • 2021-03-16
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      相关资源
      最近更新 更多