python - python Codio练习中的异常问题
问题描述
我有以下代码也调用下面的函数。它加载可以包含类似文本的文件
样本 1(它应该返回损坏的文件)
101 90 20,
abracadabra 45 30
样本 2(在这种情况下是函数提高值错误)
101 90 20
122 50 70
样本 3(在这种情况下,该函数可以很好地计算)
101 90 20
122 70 50
另外;如果用户输入一个不存在的文件,它也会出现错误。
问题:
我下面的代码工作正常,除了在任何情况下都打印出 s 的值,我只想在文件良好时打印 exeptions 或计算。
以上。
如果我从函数中删除打印,它将很好地捕获所有异常,但如果数字类型正确,它不会打印出结果
from calculate_mark import calculate_mark
try:
infile= open(input("enter a file name" ), "r" )
s=infile.read().splitlines()
for x in s:
print (calculate_mark(x))
except SyntaxError:
print("Corrupt file.")
except ValueError:
print("Values are not correct.")
except FileNotFoundError:
print("The file does not exist.")
finally:
infile.close()
def calculate_mark(s):
parts = s.split()
if len(parts)!=3: raise SyntaxError
for part in parts:
if not part.isdigit(): raise SyntaxError
mark = int(parts[1])
penalty = int(parts[2])
if penalty > mark: raise ValueError
return parts[0]+" "+str(mark-penalty)
codio的输出是
Check 1 passed
Check 2 failed
Output:
101 70
Corrupt file.
Expected:
Corrupt file.
Feedback:
We tried with marks_file_4.txt in the Filetree.
Check 3 failed
Output:
101 70
Values are not correct.
Expected:
Values are not correct.
Feedback:
We tried with marks_file_5.txt in the Filetree.
Check 4 passed
Show diff
解决方案
问题是因为错误不必出现在 txt 文件的第一行。
这意味着如果损坏的部分是文件的第一行,则代码将按预期工作,否则它将计算第一行并稍后找到错误。
例如:
abracadabra 45 30 #issue found, outputs corrupt file
101 90 20
Output: Corrupt file.
101 90 20 # No issue in this part, outputs computation
abracadabra 45 30 # issue found after, outputs corrupt file
Output:
101 70
Corrupt file.
解决问题:
在输出任何内容之前,我们必须检查所有行是否存在问题。
我的解决方案是添加一个检查所有行是否有效的函数,然后使用计算函数(进行以下修改):
# Add this function
def check_validity(lines):
for line in lines:
parts = line.split(" ")
if len(parts) != 3: raise SyntaxError
if any(part.isdigit() is False for part in parts): raise SyntaxError
mark = int(parts[1])
penalty = int(parts[2])
if penalty > mark: raise ValueError
#And change the calculate function as so:
def calculate_marks(line):
parts = line.split(" ")
mark = int(parts[1])
penalty = int(parts[2])
if penalty > mark:raise ValueError
return parts[0]+" "+str(mark-penalty)
# remaining code
try:
with open(input("enter a file name: " ), "r") as f:
lines = f.read().splitlines()
### Utilising our new function ###
check_validity(lines)
for line in lines:
calculate_marks(line)
except SyntaxError:
print("Corrupt file.")
except ValueError:
print("Values are not correct.")
except FileNotFoundError:
print("The file does not exist.")
推荐阅读
- javascript - 如何使 Spring、Ajax、Jquery 中的“编辑后结果”位于顶部(第一)?
- java - 想要编写一个类,以便在该类中声明的变量和方法在多个类中使用
- java - 循环依赖迫使我根据状态拆分服务和工厂。可以吗?
- html - XPATH - 在页面下方抓取 div 的内容
- javascript - 如何在加载时删除一个类?
- db2 - 为什么在 DB2 中运行选择查询会抛出字符串“DECFLOAT”错误?
- git - 重新定位不相关分支的一部分
- android - 如何删除对话框的白角(不是 AlertDialog 或 DialogFragment)?
- c# - How to configure cascade delete where there are cycles and multiple cascade paths
- if-statement - 谷歌表格查询+IFS功能