Pyhton exercise : Raise the exception SyntaxError if s is NOT in the format specified above

159 Views Asked by At

I am doing an excercise on codio where I am asked to

Raises the exception SyntaxError if s is NOT in the format specified above Raises the exception ValueError if s is in the format above, but penalty is a greater number than mark

Now the code below works perfectly fine, I am sure that I am not too far, but missing something

when I test my code in codio I get the following

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 : ----------------------------------------------------------------------

WE TRIED: calculate_mark("john xx 30") and did not get SyntaxError exception

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") 

1

There are 1 best solutions below

2
Nils Werner On

You have to actually raise the Exception:

raise SyntaxError()

and to clean it all up

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"))