Tell us what’s happening:
I messed up somewhere and when printing the output of the function, it only shows the end result for the last item in the list. Can someone point me in the right direction? Thanks.
Your code so far
def arithmetic_arranger(problems, show_answers=False):
if len(problems) > 5:
print('Error: Too many problems.')
else:
for problem in problems:
problem_split = problem.split()
num_x = problem_split[0]
operator = problem_split[1]
num_y = problem_split[2]
answer = 0
if operator == '*' or operator == '/':
print("Error: Operator must be '+' or '-'.")
elif not num_x.isdigit() or not num_y.isdigit():
print('Error: Numbers must only contain digits.')
elif len(problem_split[0]) > 4 or len(problem_split[2]) > 4:
print('Error: Numbers cannot be more than four digits.')
if operator == '+':
answer = int(num_x) + int(num_y)
else:
answer = int(num_x) - int(num_y)
operator_alignment = max(len(num_x), len(num_y)) + 1
dashes = max(len(num_x), len(num_y)) + 2
num_x_space = (dashes - len(num_x)) * ' '
num_y_space = (operator_alignment - len(num_y)) * ' '
answer_space = (dashes - len(str(answer)))
space = ' '
a = f'{num_x_space}{num_x}{space}\n'
b = f'{operator}{num_y_space}{num_y}{space}\n'
c = f'{dashes*"-"}{space}\n'
d = f'{answer_space*" "}{answer}{space}\n'
if show_answers:
formatted = a + b + c + d
else:
formatted = a + b + c
return formatted
print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49", "5 + 7"], True))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:139.0) Gecko/20100101 Firefox/139.0
Challenge Information:
Build an Arithmetic Formatter Project - Build an Arithmetic Formatter Project