I want to print a number of math operations (additions or subtractions) next to each other. All numbers should be right-aligned.
Below is my current code, which prints each math operation on consecutive lines (vertical output) instead of on the same lines (horizontal output).
I am not sure what method I should use here. How can I do this?
def arithmetic_arranger(problems, solution):
problems = ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]
if len(problems) > 5:
return print("Error: Too many problems.")
try:
for p in problems:
p1 = p.split(" ")
x = int(p1[0])
d = (p1[1])
y = int(p1[2])
if x > y:
e = "-" * len(str(x)) + "--"
else:
e = "-" * len(str(y)) + "--"
if len(str(x)) > 4 or len(str(y)) > 4:
return print("Error: Numbers cannot be more than four digits.")
if d == "+":
sol = x + y
elif d == "-":
sol = x - y
else:
return print("Error: Operator must be '+' or '-'.")
if solution is True:
sol = sol
elif solution is False:
sol = ""
math = ("{}\n{}" + " " + "{}\n{}\n"+" "+"{}").format(x, d, y, e, sol)
print(math)
print("====================")
except ValueError:
return print("Error: Numbers must only contain digits.")
arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"], True)
Expected output:
32 3801 45 123
+ 698 - 2 + 43 + 49
----- ------ ---- -----