gpt4 book ai didi

python - python错误检查

转载 作者:行者123 更新时间:2023-12-03 07:42:36 25 4
gpt4 key购买 nike

我正在使用下面的代码。如何添加错误检查。
如果有任何错误,请更换并继续阅读
例如:如果音量为N \ a或丢失,则替换为'a value'。
不要跳过行,不要停下来。

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
if line == '':
continue

stock, price, volume, stime = line
price = float(price)
volume = int(volume)

stocks.append((stock, price, volume, stime))

最佳答案

执行以下操作:

def isRecordValid(stock,price,volume,stime):
#do input validation here, return True if record is fine, False if not. Optionally raise an Error here and catch it in your loop
return True

reader = csv.reader(idata.split("\r\n"))

stocks = []
for line in reader:
if line == '':
continue

stock, price, volume, stime = line
try:
if isRecordValid(stock,price,volume,stime):
price = float(price)
volume = int(volume)
stocks.append((stock, price, volume, stime))
except Exception as e:
print "either print or log and error here, using 'except' means you can continue execution without the exception terminating your current stack frame and being thrown further up"

基本上定义另一种方法(或内联执行)以验证库存,价格,数量和时间是否都符合您的期望。我也会尝试在这里捕获任何错误,以防您的float()或int()调用出于任何原因将价格和交易量字符串转换为预期类型失败。

关于python - python错误检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3660370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com