首页 > 解决方案 > ValueError:我的程序中 int() 的无效文字以及 except 中的 if 语句

问题描述

我有一个程序,它接受输入并将其添加到列表中并吐出所述列表的平均值。我想做它,这样你就可以键入 MENU,它会停止 programy() 并让你退出或重新启动 programy()。一切正常,直到您键入 MENU(全部大写)。谢谢大家!:) 对 python 来说还是新手。

from functools import reduce

def programy():
    running = True

    print("I output the average of a list that you add files to.")
    listy = []

    while running == True:
        def listaverage(givenlist):
            print(sum(listy) / len(listy))

        currentnum = input("Please type a number to add to the list: ")

        try:
            val = int(currentnum)
        except ValueError:
            if str(currentnum) == "MENU":
                running = False
            else:
                print("Not a number!")
                continue

        listy.append(int(currentnum))
        listaverage(listy)

    answer = input("Please type either: EXIT or RESTART")

    if str(answer) == "RESTART":
        running = True
    if answer == "EXIT":
        exit

programy()
Traceback (most recent call last):
  File "C:\Users\hullb\OneDrive\Desktop\average_via_input.py", line 34, in <module>
    programy()
  File "C:\Users\hullb\OneDrive\Desktop\average_via_input.py", line 24, in programy
    listy.append(int(currentnum))
ValueError: invalid literal for int() with base 10: 'MENU

标签: pythonintliteralsvalueerrorexcept

解决方案


错误很简单,您将一个字符串作为输入,例如是否退出循环,即 MENU,并且在行中

listy.append(int(currentnum))

您正在将其类型转换为整数。这就是您收到上述错误的原因。无需更改大量代码,您只需移动几行即可完成。动起来

    listy.append(int(currentnum))
    listaverage(listy)

在 try 块下,如果它是一个数字,则按要求执行。还要在主程序之外定义函数 listaverage(listy) ,除非您希望它充当生成器。


推荐阅读