python-3.x - Python 中函数连续性的问题

标签 python-3.x function

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

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() 函数。然而由于某种原因,程序除了跳到脚本末尾(“按键关闭程序”命令)之外什么也不做,而没有使用 newsession() 函数。这对于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()

关于python-3.x - Python 中函数连续性的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43647022/

相关文章:

python - 使用 igraph python 从图中提取某个组件

python - 使用 importlib.util 检查库时出错

python - 根据另一个列表中的值从元组列表中删除重复值

Python - 标准库 - ascii( ) 函数

javascript - 向函数添加自定义属性

c++ - 需要在C++中将函数分配给变量

python - 从父类访问命名元组中的派生属性

c - 将新元素添加到c中的结构数组

Python将列表作为参数传递

计算复利百分比的Python函数