'Problem with reset button calculator and more - Python

This is a python calculator. I developed a part here. but, In this calculator, when the user enters two wrong numbers or one wrong operator, the reset function is given by $ + enter. How to add reset capability to code?

How to use the select_op function in Conditions correctly?

How to print the menu again at the end of all activities?

while True:

print("Select operation.")
print("1.Add      : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide   : / ")
print("5.Power    : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset    : $ ")


# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
print(choice)

if choice in ('1', '2', '3', '4', '5', '6', '7', '8'):
  num1 = float(input("Enter first number: "))
  num2 = float(input("Enter second number: "))
  
  #calculate user input numbers
  if(select_op(choice) == 1):
      print(num1 , " + " , num2 , " = " , add(num1,num2))
    
    elif(select_op(choice) == 2):
      print(num1 , " - " , num2 , " = " , subtract(num1,num2))  
      
    elif(select_op(choice) == 3):
      print(num1 , " * " , num2 , " = " , multiply(num1,num2))
      
    elif(select_op(choice) == 4):
      print(num1 , " / " , num2 , " = " , divide(num1,num2))
    
    elif(select_op(choice) == 5):
      print(num1 , " ^ " , num2 , " = " , power(num1,num2))
    
    elif(select_op(choice) == 6):
      print(num1 , " % " , num2 , " = " , remainder(num1,num2)) 
      
    elif(select_op(choice) == 7):
      print(num1 , " # " , num2 , " = " , terminate(num1,num2)) 
      
    else:
        print("Not a valid number,please enter again")

else:
    print("Unrecognized operation")
      
#program ends here
print("Done. Terminating")
exit()


Solution 1:[1]

I am having some difficulty fully understanding what you need to do; however, I'll try to answer according to my best understanding.

So, if the input is messed up, do you want to reset the code? You can put the whole code (except the last two lines of course) inside a while True: and use the keywords break and continue.

For instance, if the calculation is correct and done, modify the code to include break after each calculation, like so:

        elif(select_op(choice) == 7):
            print(num1 , " # " , num2 , " = " , terminate(num1,num2)) 
            break
        else:
            print("Not a valid number,please enter again")

This tells Python to exit the loop it is in, in this case, it is the while True: loop.

If something is messed up, you can use continue like so:

    else:
        print("Unrecognized operation")
        continue

This tells Python to disregard the rest of the code and get back to the top of the nearest loop.

To clear the terminal windows as if the script is just starting you can use @RumbleFish recommendation of using system('cls').

How to print the menu again at the end of all activities?

You can put the menu code inside a function and then call it at the beginning and at the end. This is one use of functions; not repeating the same code.

How to use the select_op function in Conditions correctly?

This really baffles me, because you didn't provide the definition for select_op. Why do you even need that? Do you have some exception handling inside? If there is no exception handling, you can just change choice to int using int() like this: choice = int(input("Enter choice(+,-,*,/,^,%,#,$): ")

Instead of having all these cases, consider using a dictionary where each key maps to the string of the operation and the function; for example: choice_dict = {1:("+",add), 2:("-",subtract)} and change the prints to

print(num1 , choice_dict[select_op(choice)][0] , num2 , " = " , choice_dict[select_op(choice)][1](num1,num2))  
break

This works because Python allows you to put the name of the functions (add, subtract, ...) as variables. For example:

def add(x,y):
        return x + y
alias = add
print(alias(1,2))

Which returns 3, as if we had called add.

Note: I think if(select_op(choice) == 1): is not correctly indented .

I tried to answer your questions to my best understanding, please tell me if that's not what you wanted or if I've missed something.

Solution 2:[2]

Your stuff isn't indented properly. Your code should look like this...

from os import system

while True:
    system('cls') #change cls to clear if this doesn't work
    print("Select operation.")
    print("1.Add      : + ")
    print("2.Subtract : - ")
    print("3.Multiply : * ")
    print("4.Divide   : / ")
    print("5.Power    : ^ ")
    print("6.Remainder: % ")
    print("7.Terminate: # ")
    print("8.Reset    : $ ")


    # take input from the user
    choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
    print(choice)

    num1 = ''
    num2 = ''
    while True:
        if num1 != '1' and num1 != '2' and num1 != '3' and num1 != '4' and num1 != '5' and num1 != '6' and num1 != '7' and num1 != '8' and num1 != '9' and num1 != '0' or num2 != '1' and num2 != '2' and num2 != '3' and num2 != '4' and num2 != '5' and num2 != '6' and num2 != '7' and num2 != '8' and num2 != '9' and num2 != '0':
            num1 = input("Enter first number: ")
            num2 = input("Enter second number: ")
        else:
            float(num1)
            float(num2)
            break
    
    #calculate user input numbers
    if(select_op(choice) == 1):
        print(num1 , " + " , num2 , " = " , add(num1,num2))
        
        elif(select_op(choice) == 2):
            print(num1 , " - " , num2 , " = " , subtract(num1,num2))  
        
        elif(select_op(choice) == 3):
            print(num1 , " * " , num2 , " = " , multiply(num1,num2))
        
        elif(select_op(choice) == 4):
            print(num1 , " / " , num2 , " = " , divide(num1,num2))
        
        elif(select_op(choice) == 5):
            print(num1 , " ^ " , num2 , " = " , power(num1,num2))
        
        elif(select_op(choice) == 6):
            print(num1 , " % " , num2 , " = " , remainder(num1,num2)) 
        
        elif(select_op(choice) == 7):
            print(num1 , " # " , num2 , " = " , terminate(num1,num2)) 
        
        else:
            print("Not a valid number,please enter again")

    else:
        print("Unrecognized operation")
        
    #program ends here
    print("Done. Terminating")
    exit()

I imported system from os. By using system('cls') (change cls to clear if it doesn't work) it clears the console after every loop so that it restarts on a fresh screen. So this should fix your issue with restarting from the menu.

UPDATED ANSWER #1

Ok so I changed the bit where you get the user to enter a number. Now it will keep asking for the user input when the user inputs a letter and stops when both inputs are numbers. (I have tested this it works)

UPDATED ANSWER #2

I don't know is select_op is a function you made yourself or some kind of module. But you can just say...

if choice == '+':
    print(num1 , " + " , num2 , " = " , add(num1,num2))

And do this for the rest of them.

UPDATED ANSWER #3

You have to else statements right after the other. This causes an error

Solution 3:[3]

As I understand, 'Reset' must be an action to start the program all over again when the user enters '$' as the input choice. Likewise, '#' to end the program.

However, I'm not much of a Python developer, but as I can see, this script is incomplete.

So, it requires to define a function named select_op(operator) which takes a string argument as the operator entered by the user. According to generic signature, this function may looks like...

int select_op(string operator);

The function should enumerate through series of integers mapped to those operators like a dictionary or name-value collection.

As per my understanding, the function may look like...

def select_op(key):
  operatorEnum = {
    '+': 1,
    '-': 2,
    '*': 3,
    '/': 4,
    '^': 5,
    '%': 6,
    '$': 7
  }
  return operatorEnum.get(key)

My suggestion

I would rather break this entire script to separate independent functions to control the execution flow clearly. Then define a driver function to wire-up each functions as per the logic. In that case, it would be easy to restart (aka "reset") or exit (aka "terminate") the application. For example,

def showMenu():
  print("Select operation.")
  print("1.Add      : + ")
  print("2.Subtract : - ")
  print("3.Multiply : * ")
  print("4.Divide   : / ")
  print("5.Power    : ^ ")
  print("6.Remainder: % ")
  print("7.Terminate: # ")
  print("8.Reset    : $ ")

def main():
  showMenu()

  # ...

  if choice == '$':
    main()

  # ... or ...

  if select_op(choice) == 7:
    main()

  # ...

  if choice == '#':
    print('Done. Terminating')
    exit()

  # ...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mohamed Yasser
Solution 2
Solution 3