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
listaverageoutside the loop: No need to redefine the function every time the loop runs—it's inefficient and unnecessary. - Moved append/average logic inside the
tryblock: We only add the number and calculate the average if the conversion to int succeeds, which keeps invalid inputs from touching the list. - Added
breakafterMENUdetection: This jumps out of thewhileloop 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 reduceline 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
相关产品推荐
相关产品推荐

