Ask coding questions

← Back to all posts
Can't pass the test. This code runs fine when I test it in IDLE.
victoria633 (0)

def arithmetic_arranger(problems, show_answer=False):

if len(problems) > 5:
    return print("Error: Too many problems.")

line1 = ""
line2 = ""
line3 = ""
line4 = ""
result = ""
space = "    "

for problem in problems:
    item=problem.split()
    
    try:
        num1=item[0]
        operator=item[1]
        num2=item[2]
    
    except IndexError:
        return print("Input is not properly formatted.")
    

    if len(num1) > 4 or len(num2) > 4:
        return print("Error: Numbers cannot be more than four digits.")

    if operator in ("+", "-"):
        pass
    else:
        return print("Error: Operator must be '+' or '-'.")

    try:
        result = str(eval(num1 + operator + num2))

    except NameError and SyntaxError:
        return print("Error: Numbers must only contain digits.")
    
    width = max(len(num1), len(num2)) + 2
    line1 += num1.rjust(width) + space
    line2 += operator + num2.rjust(width - 1) + space
    line3 += str("-" * (width) + space)
    line4 += result.rjust(width) + space

if show_answer==True:
    arithmetic_arranger = print(line1 + "\n" + line2 + "\n" + line3 + "\n" + line4)
else:
    arithmetic_arranger = print(line1 + "\n" + line2 + "\n" + line3)

return arithmetic_arranger