-1

我正在要求我在 codio 上进行练习

如果 s 不是上面指定的格式,则引发异常 SyntaxError 如果 s 是上面指定的格式,则引发异常 ValueError,但惩罚是大于标记的数字

现在下面的代码工作得很好,我相信我并没有走得太远,但错过了一些东西

当我在 codio 中测试我的代码时,我得到以下信息

FAIL: test_2 (test_calculate_mark.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/codio/workspace/.guides/secure/calculate_mark/test_calculate_mark.py", line 17, in test_2
    calculate_mark("john xx 30")
AssertionError: SyntaxError not raised : ----------------------------------------------------------------------

我们尝试过: calculate_mark("john xx 30")并没有SyntaxError例外

def calculate_mark(s):

  mystring= s.split()

  m=s.replace(" ", "")
  try:
    
    assert m.isdigit() == True, "SyntaxError"
    student_number=(mystring[0])
    student_mark=int((mystring[1]))
    student_penanlty=int((mystring[2]))
    assert student_penanlty <student_mark , "ValueError"
    mycalc=student_mark-student_penanlty
    final_mark=student_number + " "+  str(mycalc)
    return final_mark

  except AssertionError as msg:
    print(msg)



calculate_mark("123 35 50") 

4

1 回答 1

1

你实际上raise必须例外:

raise SyntaxError()

并把它清理干净

def calculate_mark(s):
    splits = s.split()

    try:
        splits = [int(s) for s in splits]
    except ValueError:  # at least one of splits is not an integer
        raise SyntaxError("Please pass exactly three integer strings")

    number, mark, penalty = splits

    if penalty < mark:
        raise ValueError("penalty must be larger than mark")
    
    return f"{number} {mark - penalty}"

print(calculate_mark("123 35 50"))
于 2021-11-04T21:42:01.273 回答