python - 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
解决方案
错误很简单,您将一个字符串作为输入,例如是否退出循环,即 MENU,并且在行中
listy.append(int(currentnum))
您正在将其类型转换为整数。这就是您收到上述错误的原因。无需更改大量代码,您只需移动几行即可完成。动起来
listy.append(int(currentnum))
listaverage(listy)
在 try 块下,如果它是一个数字,则按要求执行。还要在主程序之外定义函数 listaverage(listy) ,除非您希望它充当生成器。
推荐阅读
- python - iNotify 收到事件后如何关闭文件句柄
- python-3.x - 将变量从一个函数调用到另一个函数的问题
- php - 通过函数创建数组
- android - 无法从 json 下载多个视频文件并将下载路径设置为同一个列表
- r - 使用非正态分布的线性固定效应模型(添加直方图)
- python - 如何将数据集输入到 Python 的 SwarmPackage 中的 Swarm 算法,以及如何提取优化后的特征列表给分类器提供输入?
- ios - 创建一个由图标制作的按钮,以便图标填充它
- node.js - 运行简单的节点 js 服务器
- ios - 向 UISegmentControl 添加自定义边框
- python - 如何将 Dask Dataframe 转换为 Dask Array?