- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 python3
编写一个函数,使用异常处理
。我认为 ValueError
是检查值是否在给定范围内的正确工具,如给定的 here in python3 doc其中说:
function receives an argument that has the right type but an inappropriate value
因此,在我的这个小片段中,我希望使用 ValueError 来检查未执行的范围 (0-1):
while True:
try:
imode = int(input("Generate for EOS(0) or S2(1)"))
except (ValueError):
print("Mode not recognised! Retry")
continue
else:
break
print(imode)
产生:
Generate for EOS(0) or S2(1)3
3
当然,我可以像这样进行值检查:
if (imode < 0 or imode > 1):
print("Mode not recogised. RETRY!")
continue
else:
break
但是 ValueError 似乎确实在做这件事。
这里有几个关于 ValueError
的问题,但没有一个检查“不适当的值,例如 this我是新手,python 不是我的主要语言。请给我一些见解。
最佳答案
我认为您误解了什么是 ValueError
(通常是 Exception
)。
Exceptions
是方法向其调用者发出信号的一种方式,表明已遇到某些严重错误情况,会阻止该方法按预期执行。 Python 的 try-except-finally
控制结构为调用者提供了一种检测这些错误条件并做出相应 react 的方法。
ValueError
是一种标准的 Exception
,由执行某种范围检查的各种方法引发,以表明提供给该方法的值超出了有效范围。换句话说,它是一种发出错误情况信号的通用方式。 ValueError
本身不做任何类型的检查。还有很多像这样的其他标准异常
; KeyError
表示您试图访问不存在的映射结构(如 dict
或 set
)中的键, IndexError
表示您试图将类似列表的结构索引到无效位置等。它们本身并没有真正做任何特殊的事情,它们只是一种直接指定确切问题类型的方法被调用的方法遇到。
Exceptions
与 python 中的成语密切相关,它通常被认为是 'easier to ask forgiveness than permission' .当然,许多语言都支持异常,但 Python 是为数不多的语言之一,您会经常看到代码中的 Exception
情况实际上是一种通常遵循的代码路径,而不是仅在发生某些事情时才会发生的代码路径真的错了。
下面是一个正确使用 ValueError
的例子:
def gen(selection):
if imode == 0:
# do EOS stuff here
elif imode == 1:
# do S2 stuff here
else:
raise ValueError("Please Select An Option Between 0-1")
def selector():
while True:
try:
gen(int(input("Generate for EOS(0) or S2(1)")))
break
except ValueError as e: # This will actually satisfy two cases; If the user entered not a number, in which case int() raises, or if they entered a number out of bounds, in which chase gen() raises.
print(e)
请注意,可能有更直接的方法来执行您想要的操作,但这只是作为如何正确使用 ValueError
的示例。
关于python3 ValueError值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26978299/
我正在尝试并行运行具有循环返回值的函数。但它似乎停留在 results = pool.map(algorithm_file.foo, population) 在 for 循环的第二次迭代中 r
Serving Flask 应用程序“服务器”(延迟加载) 环境:生产警告:这是一个开发服务器。不要在生产部署中使用它。请改用生产 WSGI 服务器。 Debug模式:开启 在 http://0.0.
我使用“product.pricelist”模型中的 get_product_price_rule() 函数。我的代码是: price = self._get_display_price(produ
我收到以下错误: Traceback (most recent call last): File "/home/odroid/trackAndFollow/getPositions.py", line
我正在尝试采用机器学习方法,但遇到了一些问题。这是我的代码: import sys import scipy import numpy import matplotlib import pandas
我尝试使用 tensorflow 1.4.0 对我的原始记录进行分类。过程如下。 拳头:读取图片和标签,输出“tfrecord”格式的文件。第二:读取tf记录和训练 编写tfrecord脚本是 !/u
我是新手,所以需要任何帮助,当我要求一个例子时,我的教授给我了这段代码,我希望有一个工作模型...... from numpy import loadtxt import numpy as np fr
我无法弄清楚为什么会出现此 ValueError...为了提供一些上下文,我正在使用 requests、BeautifulSoup 和 json 与 python 来抓取站点 json 数据。 我不确
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我只有四个星期的 Python 经验。使用 Tkinter 创建一个工具,将新的公司 Logo 粘贴到现有图像之上。 下面的方法是获取给定目录中的所有图像并将新 Logo 粘贴到初始级别。现有图像、编
我只有四个星期的 Python 经验。使用 Tkinter 创建一个工具,将新的公司 Logo 粘贴到现有图像之上。 下面的方法是获取给定目录中的所有图像并将新 Logo 粘贴到初始级别。现有图像、编
我在尝试在 Keras 2.0.8、Python 3.6.1 和 Tensorflow 后端中训练模型时遇到问题。 错误消息: ValueError: Error when checking targ
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我有这段代码: while True: try: start = int(input("Starting number: ")) fin = int(i
我是 python 的初学者编码员,试图制作一个“模具滚筒”,您可以在其中选择模具的大小,它在我的代码的第 20 行返回此错误 import sys import random import geto
我有以下代码: import fxcmpy import pandas as pd from pandas import datetime from pandas import DataFrame a
我正在尝试使用 django 和 python 制作一个博客应用程序。我也在尝试使用 s3 存储桶进行存储,使用 heroku 进行部署。我正在学习 coreymschafer 的在线教程。我正在按照
我创建了一个 numpy 数组(考虑输入数据)并想更改顺序(一些数值运算后的输出数据)。在使用转换后的数组时,我遇到错误并找到了根本原因。请在下面找到详细信息并使用 numpy 版本 1.19.1 i
我已经引用了之前的查询 All arguments should have the same length plotly但仍然没有得到我的问题的答案。 我有一个黄金价格数据集。 Date
我是一名优秀的程序员,十分优秀!