Python功能延续的问题



我知道这可能是一个非常简单的修复程序,但是我似乎无法使代码工作。这是有问题的摘录:

def main_menu():
    print("Welcome! Please Choose An Option to Proceed")
    print("1. New: Input Letters Into A New Excel Document")
    print("2. Add: Add New Letters To An Existing Excel Document")
    while True:
        choice = input("Enter Option Number: ")    
        if choice.lower() in ['1','2']:
            return choice.lower()
        else:
            print("Invalid Number Choice")
            continue
def menu_choice(main_menu):
    while True:
        choice = main_menu()
        if choice == "1":
            newsession()
        elif choice == "2":
            addsession()
        else:
            break
def newsession():
    while True:
        try:    
            txtfilenameinput = input("1. Enter 'Txt' Input File Name: ")
            inputfilename = txtfilenameinput.replace(".txt" , "")
            inputfile = codecs.open(inputfilename + ".txt" , "r" , encoding = "utf-8" , errors = "ignore")
            print("File Found" + "n")
            break
        except FileNotFoundError:
            print("File Not Found: Make Sure The File Is Spelled Correctly And That Both The Program and File Is On The Desktop Screen" + "n")
if __name__ == '__main__':
    main_menu()
closeprogram = input("Press Enter Key To Close Program")

我的目标是,例如,当在main_menu((中插入" 1"的输入时,脚本将开始运行newsession((函数。然而,出于某种原因,该程序无需跳到脚本的末尾(即"关闭程序的按键"命令(,而无需参与NewsSession((函数。对于addSession((函数的" 2"输入也是如此。我究竟做错了什么?我已经尝试了所有事情,但是什么都没有允许我选择1或2的输入来继续脚本中的进度。谢谢您的帮助!

尝试以下代码。它允许从程序退出,并一次又一次返回以获取更多用户输入:

def main_menu():
    print("Welcome! Please Choose An Option to Proceed")
    print("1. New: Input Letters Into A New Excel Document")
    print("2. Add: Add New Letters To An Existing Excel Document")
    print(" QUIT with 'q'")
    while True:
        choice = input("Enter Option Number: ")    
        if choice.lower() in ['1','2','q']:
            return choice.lower()
        else:
            print("Invalid Number Choice")
            continue
def menu_choice(main_menu):
    while True:
        choice = main_menu()
        if choice == "1":
            newsession()
        elif choice == "2":
            addsession()
        else:
            break

您的代码问题是您被"被困"到while True:循环中而无需逃脱。因此,在一次又一次启动了一个用户选择newsession()addsession()之后,脚本没有进一步的进展,除了杀死程序之外,无法更改任何内容。请记住:每个while True循环至少应具有包含brakereturn的一行,否则这是一个永无止境的故事...

未达到newsession()的问题在这里:

if __name__ == '__main__':
    main_menu()

应该在哪里:

if __name__ == '__main__': menu_choice()

最新更新