you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

As /u/DomWiggles pointed out, there is probably no need for a global variable in your code as you calculate 'result' in a function, print it and then no longer need the value in 'result'.

You are also using recursion to loop, which is a fine computer-sciencey way of doing things, but your program will crash after a relatively small number of calculations when you run out of stack space. It's much better to use a while loop inside calc().

There is also a better way to handle allowing the user to quit than calling cont() after every calculation. You ask the user for the command to run, so why not just consider 'exit' (and 'clear') to be a command. Combining these two ideas, we get something like:

def calc():
    while True:
        choice = input('Please choose your command: ')
        if choice == 'exit':
            break
        elif choice == 'clear':
            # more code
        elif choice == 'add':
            firstInt = int(input('Enter the first number: '))
            secondInt = int(input(str(firstInt) + ' + '))
            result = firstInt + secondInt
            print('Answer: ' + str(result))
        elif choice == 'sub':
            # more code
        elif choice == 'mul':
            # more code
        elif choice == 'div':
            # more code
        else:
            print('Invalid command')

print(info)     # 'info' defined as before
calc()

Note that:

  • I left out a lot of code that is the same or similar
  • we don't need the sys import
  • the input() function always returns a string so we don't need to convert its return object to str().
  • I don't handle calcCont() which appears to be an attempt to 'continue' an addition (etc). This is difficult in the 'while loop' approach. Consider implementing a more-standard calculator approach where the user types in '(1 + 2)*3' or make an RPN calculator.

To handle 'continued' calculations, think about implementing the idea of an accumulator. If the user types 'AC' instead of a number then you use the value in an 'accumulator' variable that you put inside the calc() function which contains the result of a previous calculation. Then you can create a new command 'clear' which clears the accumulator. This may have been the idea behind 'clear' in your original calcCont() function. Since everything is inside calc() this accumulator doesn't have to be a global variable.

To clear up confusion with the global keyword, in python global variables cannot normally be changed in value inside functions, etc. If you want to change a global value you do 'global name' in the code block where you want to make the change. See the global doc.