【问题标题】:troubles with exceptions in python Codio exercisepython Codio练习中的异常问题
【发布时间】:2021-12-19 09:32:03
【问题描述】:

我有下面的代码也调用下面的函数。 它加载可以包含类似文本的文件

示例 1(它应该返回损坏的文件)
101 90 20,
阿布拉卡达布拉 45 30

示例 2(在本例中为函数升值错误)
101 90 20
122 50 70

样本 3(在这种情况下,函数可以很好地计算)
101 90 20
122 70 50

另外;如果用户输入了一个不存在的文件,也会报错。


问题:
我下面的代码工作正常,除了在任何情况下都打印出 s 的值,我只想在文件良好时打印异常或计算。


以上内容。
如果我从函数中删除打印,它会很好地捕获所有异常,但如果数字类型正确,它不会打印出结果

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

【问题讨论】:

  • 在你给出的例子中,你的意思是每行有 3 个值吗? 101 marks penalty。而不是您示例中的 6 个?
  • 我真的不明白你的问题是什么。你能提取并提供一个minimal reproducible example吗?另外,预期和实际输出是多少?
  • 我已经添加了 codio 的输出

标签: python exception except


【解决方案1】:

问题是因为错误不必在 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.")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多