Search code examples
pythoncalculatorresettry-except

How do I reset my calculator, when I enter "$" to input , instead of a number , python


I need to reset this calculator when user enter "$" instead first or second input number or user enter "$" end of the input number (ex: 5$,20$).

the (a,b) is input number1 and number2. it was assigned as global varibles.

select_op(choice) is function, running the operation that user need. input_function() is function for input two numbers.

# Functions for arithmetic operations.


def add(a,b):
    return (a+b)        # 'a' and 'b' will add.

def subtract(a,b):
    return (a-b)        # 'b' substract from 'a'.

def multiply(a,b):
    return (a*b)        #'a' multiply by 'b'.

def divide(a,b):
    if b == 0 :         .
        return None
    else:
        return (a/b)    # 'a' divided by 'b'.

def power(a,b):
    return (a**b)       # 'a' power of 'b'.

def remainder(a,b):
    if b == 0:           
        return None
    else:
        return (a%b)    # reminder of 'a' divided by 'b'.


#this function for out put of operation

def select_op(choice):      #this function will select operation
    if choice == "+":
        input_function()
        print(a,' + ',b,' = ',add(a,b))
    elif choice == "-":
        input_function()
        print(a,' - ',b,' = ',subtract(a,b))
    elif choice == "*":
        input_function()
        print(a,' * ',b,' = ',multiply(a,b))
    elif choice == "/":
        input_function()
        if b==0:                            
            print("float division by zero")
        print(a,' / ',b,' = ',divide(a,b))
    elif choice == "^":
        input_function()
        print(a,' ^ ',b,' = ',power(a,b))
    elif choice == "%":
        input_function()
        if b==0:                           
            print("float division by zero")
        print(a,' % ',b,' = ',remainder(a,b))
    elif choice == "#":                    #if choice is '#' program will terminate.
        return -1
    elif choice == "$":                    #if choice is '$' program reset.
        return None
    else:
        print("Unrecognized operation")



#this function for input two operands.
def input_function():
    number1=float(input("Enter first number: "))
    number2=float(input("Enter second number: "))
    global a,b
    a=number1
    b=number2
    return a,b


#loop repeat until user need to terminate.


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(select_op(choice) == -1):
    #program ends here
    print("Done. Terminating")
    exit()

Solution

  • Be sure to check whether the string returned from input() ends with a "$" before converting it to a float.

    To reset when a user types something that ends with "$", you could throw an exception to break out of your calculator logic and start over. We'll surround the stuff inside your while loop with a try/catch, so that the exception doesn't stop your program, but merely starts a new iteration in the while loop.

    
    # I omitted all your other functions at the start of the file
    # but of course those should be included as well
    
    class ResetException(Exception):
        pass
    
    #this function for input two operands.
    def input_function():
        s = input("Enter first number: ")
        if s.endswith("$"):
            raise ResetException()
        number1=float(s)
        s = input("Enter second number: ")
        if s.endswith("$"):
            raise ResetException()
        number2=float(s)
        global a,b
        a=number1
        b=number2
        return a,b
    
    
    #loop repeat until user need to terminate.
    
    
    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
      try:
        choice = input("Enter choice(+,-,*,/,^,%,#,$): ")
        print(choice)
    
        if(select_op(choice) == -1):
          #program ends here
          print("Done. Terminating")
          exit()
      except ResetException:
        pass