You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序输入MENU触发ValueError求助:实现菜单退出/重启功能

Hey Brad, let's work through why your MENU input is throwing that error!

The Root Cause

When you type MENU, your code enters the except ValueError block, sets running=False, but then still continues to the listy.append(int(currentnum)) line outside the try/except block. Since currentnum is "MENU" (not a valid integer), converting it to int fails here, causing the ValueError you see in the traceback.

The Fixed Code + Improvements

Here's adjusted code that fixes the error, plus some small tweaks to make the program cleaner and more user-friendly:

def listaverage(givenlist):
    print(sum(givenlist) / len(givenlist))

def programy():
    running = True
    print("I output the average of a list that you add numbers to.")
    listy = []
    while running:
        currentnum = input("Please type a number to add to the list: ")
        try:
            val = int(currentnum)
            listy.append(val)
            listaverage(listy)
        except ValueError:
            if currentnum == "MENU":
                running = False
                break  # Exit the loop immediately to skip the append step
            else:
                print("Not a number!")
                continue
    answer = input("Please type either: EXIT or RESTART: ")
    # Make input case-insensitive for better user experience
    if answer.strip().upper() == "RESTART":
        programy()
    elif answer.strip().upper() == "EXIT":
        exit()

programy()

Key Changes Explained:

  • Moved listaverage outside the loop: No need to redefine the function every time the loop runs—it's inefficient and unnecessary.
  • Moved append/average logic inside the try block: We only add the number and calculate the average if the conversion to int succeeds, which keeps invalid inputs from touching the list.
  • Added break after MENU detection: This jumps out of the while loop right away, so we never reach the code that would try to append "MENU" to the list.
  • Case-insensitive exit/restart: Users can type lowercase, uppercase, or even inputs with extra spaces, and the program will still recognize their choice (remove .strip().upper() if you want strict case matching).
  • Removed unused imports: The from functools import reduce line was never used, so I cleaned it up.
  • Fixed a tiny typo: Changed "add files to" to "add numbers to" in the intro print statement—assuming that was a small mistake!

This should resolve the error and make your program work as intended when you input MENU.

内容的提问来源于stack exchange,提问作者BradStrat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 15:22:47