0

I'm new to Python and I am building a simple interactive calculator as a project. When I run the code in the terminal, it takes all the inputs but does not return the final output. The code restarts instead and asks for inputs again. I'd like to know where I'm going wrong.

Here's the code:

def solver():
    
    while True:
        try:
            arg1 = float(input('Add 1st number: '))
            arg2 = float(input('Add 2nd number: '))
        except ValueError:
            print('Invalid input. Please enter a number')
            continue
        
        allowed_functions = set(['+', '-', '/', '*'])
        try:
            function = input('Please choose operation from [+, -, *, /]: ')
        except function not in allowed_functions:
                print(f'Function must contain mathetmatical operation values only')
                continue
                
        
        #empty formatting strings         
        first_line = ""
        second_line = ""
        dashes = ""
        solutions = ""


        #define mathematical operations
        if function == '+':
            output = arg1 + arg2
        elif function == '-':
            output = arg1 - arg2
        elif function == '*':
            output = arg1 * arg2
        elif function == '/':
                if arg2 == 0:
                    print(f'Division by 0 not possible')
                    continue
                else:
                    output = arg1 / arg2
            

        #convert values to strings for formatting    
        str_arg1 = str(arg1)
        str_arg2 =  str(arg2)
        str_output = str(output)

        #output format
        width = max(len(str_arg1), len(str_arg2)) + 2
        top = str_arg1.rjust(width)
        bottom = function + str_arg2.rjust(width-1)
        lines = '-' * width
        result = str_output.rjust(width)


        first_line += top
        second_line += bottom
        dashes += lines
        solutions += result

        #final output    
        problems = f'{first_line}\n{second_line}\n{dashes}\n{solutions}'
        return problems

        quit_program = input('Quit Program? Y/N: ')
        if quit_program == 'Y' or quit_program == 'y':
                break

solver()
4
  • There are numerous issues with your code. Try entering something other than +-*/ and see what happens. The "Quit program?" prompt will never appear because it is preceded by return. I recommend that you familiarise yourself with pylint (or similar) Commented Aug 31 at 19:13
  • You might try one of the available tools that do similar things (asteval or simpleeval), then make simple edits to it if you need to. Commented Aug 31 at 19:31
  • 1
    The return value of a program is not printed in the terminal. Try the print function, instead. Commented Aug 31 at 19:50
  • it takes all the inputs but does not return the final output What does that mean? Do you mean it doesn't print the final output? Well, of course it doesn't, because you didn't tell it to do that. If you want something to be printed, you have to use print(), which you did not do. Commented Sep 1 at 4:56

2 Answers 2

1

The reason the solution is not getting printed is in this line:

return problems

The return keyword doesn't show anything on the console; it makes it so the function passes that value where the function is being called. To show statements on the console, use the print function instead:

print(problems)

There are one place where your logic can be improved:

Invalid Operation Handling:

  1. try:
        function = input('Please choose operation from [+, -, *, /]: ')
    except function not in allowed_functions:
        print(f'Function must contain mathematical operation values only')
        continue
    

    The except block only gets triggered when there is an exception, not when a condition is met, for that, you should use an if statement:

    function = input('Please choose operation from [+, -, *, /]: ')
    
    if function not in allowed_functions:
        print(f'Function must contain mathematical operation values only')
        continue
    

Also, here are some other things in your code that should be changed (for good practice):

width = max(len(str_arg1), len(str_arg2)) + 2
top = str_arg1.rjust(width)
bottom = function + str_arg2.rjust(width - 1)
lines = '-' * width
result = str_output.rjust(width)

# Delete these:
first_line += top
second_line += bottom
dashes += lines
solutions += result

There is no point in creating new variables which hold exactly the same thing as others. Not only that, you should just use = rather than +=:

width = max(len(str_arg1), len(str_arg2)) + 2
top = str_arg1.rjust(width)
bottom = function + str_arg2.rjust(width - 1)
lines = '-' * width
result = str_output.rjust(width)

problems = f'{top}\n{bottom}\n{lines}\n{result}'
print(problems)

And also, here:

if quit_program == 'Y' or quit_program == 'y':
    break

instead of repeating quit_program == "y" twice for both cases, you can just do something like this:

if quit_program.lower() == 'y':
    break

Here is another place:

if arg2 == 0:
    print(f'Division by 0 not possible')
    continue
else:
    output = arg1 / arg2

no need for the else, if the condition is True, the code below it will never be run anyway.

if arg2 == 0:
    print(f'Division by 0 not possible')
    continue
output = arg1 / arg2

Here is the full code with all of the changes:

def solver():
    while True:
        try:
            arg1 = float(input('Add 1st number: '))
            arg2 = float(input('Add 2nd number: '))
        except ValueError:
            print('Invalid input. Please enter a number')
            continue

        allowed_functions = {'+', '-', '/', '*'}

        function = input('Please choose operation from [+, -, *, /]: ')

        if function not in allowed_functions:
            print(f'Function must contain mathematical operation values only')
            continue

        # define mathematical operations
        if function == '+':
            output = arg1 + arg2
        elif function == '-':
            output = arg1 - arg2
        elif function == '*':
            output = arg1 * arg2
        elif function == '/':
            if arg2 == 0:
                print(f'Division by 0 not possible')
                continue
            output = arg1 / arg2

        # convert values to strings for formatting
        str_arg1 = str(arg1)
        str_arg2 = str(arg2)
        str_output = str(output)

        # output format
        width = max(len(str_arg1), len(str_arg2)) + 2
        top = str_arg1.rjust(width)
        bottom = function + str_arg2.rjust(width - 1)
        lines = '-' * width
        result = str_output.rjust(width)
        # final output
        problems = f'{top}\n{bottom}\n{lines}\n{result}'
        print(problems)

        quit_program = input('Quit Program? Y/N: ')
        if quit_program.lower() == 'y':
            break


solver()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I will keep these changes in mind.
Glad to help! I hope you completed your project!
1

Hey this looks like a great first project! I was able to get your code running with two tiny changes, which I will describe first and then paste the updated code below:

Change 1) Why your code does not do what you expect

If you take a look at these lines, you will notice that you are actually returning the function in the middle of the while loop instead of printing the output:

    #final output    
    problems = f'{first_line}\n{second_line}\n{dashes}\n{solutions}'
    return problems

Change 2) Not catching incorrect operators:

The try... except... block is used to Catch and handle exceptions, but it looks like your code is trying to create an exception (if the input operator is not offered) NOT handle an Exception from the input. You should just use an if statement instead, with respect to these lines:


    allowed_functions = set(['+', '-', '/', '*'])
    try:
        function = input('Please choose operation from [+, -, *, /]: ')
    except function not in allowed_functions:
            print(f'Function must contain mathetmatical operation values only')
            continue

Putting both of these together here is a working version of your code I got running:

def solver():
    while True:
        try:
            arg1 = float(input('Add 1st number: '))
            arg2 = float(input('Add 2nd number: '))
        except ValueError:
            print('Invalid input. Please enter a number')
            continue

        # UPDATED CHECKING HERE TO SEE IF EXCEPTION SHOULD BE RAISED
        function = input('Please choose operation from [+, -, *, /]: ')
        if function not in set('+-/*'):
            raise Exception(f'Function must contain mathetmatical operation values only')

        # empty formatting strings
        first_line = ""
        second_line = ""
        dashes = ""
        solutions = ""

        # define mathematical operations
        if function == '+':
            output = arg1 + arg2
        elif function == '-':
            output = arg1 - arg2
        elif function == '*':
            output = arg1 * arg2
        elif function == '/':
            if arg2 == 0:
                print(f'Division by 0 not possible')
                continue
            else:
                output = arg1 / arg2

        # convert values to strings for formatting
        str_arg1 = str(arg1)
        str_arg2 = str(arg2)
        str_output = str(output)

        # output format
        width = max(len(str_arg1), len(str_arg2)) + 2
        top = str_arg1.rjust(width)
        bottom = function + str_arg2.rjust(width - 1)
        lines = '-' * width
        result = str_output.rjust(width)

        first_line += top
        second_line += bottom
        dashes += lines
        solutions += result
        
        # UPDATED THIS TO PRINT THE PROBLEM INSTEAD OF PREMATURELY RETURNING
        # final output
        problems = f'{first_line}\n{second_line}\n{dashes}\n{solutions}'
        print(problems)

        quit_program = input('Quit Program? Y/N: ')
        if quit_program == 'Y' or quit_program == 'y':
            break

if __name__ == "__main__": solver()

1 Comment

Thank you! I see where I went wrong. The code is working now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.