Arithmetic formatter (1st Python Project)

Hey there, I’m relatively new to coding (<1year) and learned Python just recently. So last weekend I wrote the first Challenge (arithmetic formatter) in VSCode and everything works fine. However when I copy it into the Repl:.it it gives me a bunch of errors. I’ve tried to figure out how to fix it, but i think it’s fair to say that i’m officially stuck and not sure what what I’m doing wrong. Here is my code which works fine in my VSCode app.

 def arithmetic_arranger(myList, arg = False):

    firstList = []
    secondList = []
    thirdList = []
    fourthList = []

    if len(myList) > 5:
        print("Error: Too many problems.")
    else:
        for each in myList:
            eachNum = each.split(" ")
            # print("Equation:", eachNum)
            firstNum = eachNum[0]
            secondNum = eachNum[2] 
            operator = eachNum[1]
            # print("Operator:",operator)


            #checking in operand are integer:
            if firstNum.isdigit() == False:
                print("Error: Numbers must only contain digits.")
                quit()
            elif secondNum.isdigit() == False:
                print("Error: Numbers must only contain digits.")
                quit()
            

            numWidth = 0

            if len(firstNum) + 2 >= len(secondNum) + 2:
                numWidth = len(firstNum) + 2
            elif len(firstNum) + 2 <= len(secondNum) + 2:
                numWidth = len(secondNum) + 2
            
            # print("Length of first element:", len(firstNum), "Length of complete firstLine:", len(firstNum) + 2)
            # print("Length of second element:", len(secondNum), "Length of complete secondLine:", len(secondNum) + 2)
            # print("Therefore numWidth is:", numWidth, "blocks long (spaces included)")

            if numWidth > 6:
                print("Error: Numbers cannot be more than four digits.")
                quit()
            #firstLine:
            #spaceCount firstList
            spaceFirstList = []
            # print(numWidth - (len(firstNum) + 2), "spaces need to be created on the firstLine.")
            for eachSpace in range(numWidth - (len(firstNum) + 2)):
                spaceFirstList.append(" ")
            
            #printing firstList
            firstList.extend(["  "])
            firstList.extend(spaceFirstList)
            firstList.extend([firstNum, "    "])

            #secondLine:
            #spaceCount secondList
            spaceSecondList = []
            # print(numWidth - (len(secondNum) + 2), "spaces need to be created on the secondLine.")
            for eachSpace in range(numWidth - (len(secondNum) + 2)):
                spaceSecondList.append(" ")

            #printing secondList
            secondList.extend([operator, " "])
            secondList.extend(spaceSecondList)
            secondList.extend([secondNum, "    "])

            #thirdLine:
            for eachSpace in range(numWidth):
                thirdList.append("-")
        
            thirdList.extend(["    "])

            #fourthLine [Answer]:

            if arg == True:
                if operator == "+":
                    answer = int(firstNum) + int(secondNum)
                    
                    # print("The sum of equation is:", answer, "and it's length:", len(str(answer)))
                elif operator == "-":
                    answer = int(firstNum) - int(secondNum)

                    # print("The diff of equation is:", answer, "and it's length:", len(str(answer)))
                else:
                    print("Error: Operator must be '+' or '-'.")
                    quit()

                spaceFourthList = []
                for eachSpace in range(numWidth - len(str(answer))):
                    spaceFourthList.append(" ")

                fourthList.extend(spaceFourthList)
                fourthList.extend([str(answer)])
            # else:
            #     print("arg is not set to True, therefore no answer is displayed.")

            fourthList.extend(["    "])

            # print("reloop", "\n", "\n")


        #Complete Lists
        # print("\n", "FirstLine: ",firstList)
        # print("\n", "SecondLine: ",secondList)
        # print("\n", "thirdLine: ",thirdList)
        # print("\n", "fourthLine: ",fourthList)

        #String maker + space/"-" remover at end of string
        firstString = "".join(firstList).rstrip(" ")
        secondString = "".join(secondList).rstrip(" ")
        thirdString = "".join(thirdList).rstrip(" ")
        fourthString = "".join(fourthList).rstrip(" ")

        #Final product
        return_statement = firstString + "\n" + secondString + "\n" + thirdString + "\n" + fourthString

        print(return_statement)



arithmetic_arranger(["24 + 8525", "301 - 2", "45 + 43", "123 + 49"],True)

And here are the Errors Repl:.it is giving me when I run it on their platform:

 python main.py
   32      3801      45      123
+ 698    -    2    + 43    +  49
-----    ------    ----    -----

FFError: Numbers must only contain digits.
E.Error: Numbers cannot be more than four digits.
EError: Too many problems.
F
======================================================================
ERROR: test_only_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-5/test_module.py", line 32, in test_only_digits
    actual = arithmetic_arranger(["98 + 3g5", "3801 - 2", "45 + 43", "123 + 49"])
  File "/home/runner/boilerplate-arithmetic-formatter-5/arithmetic_arranger.py", line 26, in arithmetic_arranger
    quit()
  File "/usr/lib/python3.8/_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None

======================================================================
ERROR: test_too_many_digits (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-5/test_module.py", line 27, in test_too_many_digits
    actual = arithmetic_arranger(["24 + 85215", "3801 - 2", "45 + 43", "123 + 49"])
  File "/home/runner/boilerplate-arithmetic-formatter-5/arithmetic_arranger.py", line 42, in arithmetic_arranger
    quit()
  File "/usr/lib/python3.8/_sitebuiltins.py", line 26, in __call__
    raise SystemExit(code)
SystemExit: None

======================================================================
FAIL: test_arrangement (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-5/test_module.py", line 10, in test_arrangement
    self.assertEqual(actual, expected, 'Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]')
AssertionError: '    [36 chars]   -    2    + 43    +  49\n-----    ------    ----    -----\n' != '    [36 chars]   -    2    + 43    +  49\n-----    ------    ----    -----'
      3      3801      45      123
  + 855    -    2    + 43    +  49
- -----    ------    ----    -----
?                                 -
+ -----    ------    ----    ----- : Expected different output when calling "arithmetic_arranger()" with ["3 + 855", "3801 - 2", "45 + 43", "123 + 49"]

======================================================================
FAIL: test_incorrect_operator (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-5/test_module.py", line 24, in test_incorrect_operator
    self.assertEqual(actual, expected, '''Expected calling "arithmetic_arranger()" with a problem that uses the "/" operator to return "Error: Operator must be '+' or '-'."''')
AssertionError: '    3      3801      45      123\n/ 855 [58 chars]--\n' != "Error: Operator must be '+' or '-'."
+ Error: Operator must be '+' or '-'.-     3      3801      45      123
- / 855    -    2    + 43    +  49
- -----    ------    ----    -----
 : Expected calling "arithmetic_arranger()" with a problem that uses the "/" operator to return "Error: Operator must be '+' or '-'."

======================================================================
FAIL: test_too_many_problems (test_module.UnitTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/runner/boilerplate-arithmetic-formatter-5/test_module.py", line 19, in test_too_many_problems
    self.assertEqual(actual, expected, 'Expected calling "arithmetic_arranger()" with more than five problems to return "Error: Too many problems."')
AssertionError: None != 'Error: Too many problems.' : Expected calling "arithmetic_arranger()" with more than five problems to return "Error: Too many problems."

----------------------------------------------------------------------
Ran 6 tests in 0.003s

FAILED (failures=3, errors=2)

Hey @Myrmidon93,
It’s good that you built the project. Congratulations.
It would be better, if you provide the repl link.

Instead of above lines try returning the exact error statement(one which you’re printing)

1 Like

Hey, I couldn’t find any link to share, but I hope this will do the trick. https://repl.it/@Pierrek93/boilerplate-arithmetic-formatter-6#arithmetic_arranger.py

the error is because the programn exit without the function returning an output, try fixing this, make so that the function always return something


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

You need not print the output for error, instead you’ve to return it as a string, without exiting the program.
Doing these I managed to pass 4 tests, and next there are two failures:

  1. You’re not checking the operators when answer for the input is not asked(when arg=False)
  2. You’re adding new line to the output string when you need not have to calculate the result(arg=False), remove the newline at end
1 Like

Thank you a lot for helping me so fast. I’ve corrected my mistakes and handed it in. I’m impressed how you figured out so quickly what the issues were. especially the new line when ( arg == False)… Well done!

I was able to figure out quickly because, I was in your shoes when I was doing this projects. I also had the difficulty designing the output.

When I analyzed your error, I thought of the newline and found the error at exactly same place.

If you don’t mind, you can take a look at my solution for the same problem here

I also want to share a resource, PythonTutor
:arrow_up: I found this resource in this forum itself, and it’s very much helpful when dealing with this type of problems where aligning is necessary and also in complex scripts, where we need to find the exact cause of error. It’s a kind of debugger.

1 Like