Home > other >  Why is my python fuction printing the ZeroDivisionError twice?
Why is my python fuction printing the ZeroDivisionError twice?

Time:07-18

I am making a calculator in python. There is a separate function div to do the division. if the user enters zero as the second number the code is supposed print "float division by zero" as error message and return "none". But the code is printing the error twice.

enter image description here

can anyone explain why is this printing the error twice?

Here is the full code below

last_calculation = []
def add(a, b):
    try:
        return float(a)   float(b)
    except:
        return "None"


def sub(a, b):
    try:
        return float(a) - float(b)
    except:
        return "None"


def mul(a, b):
    try:
        return float(a) * float(b)
    except:
        return "None"


def div(a, b):
    try:
        return float(a) / float(b)
    except:
        print("float division by zero")
        return "None"

def power(a, b):
    try:
        return float(a) ** float(b)
    except:
        return "None"


def remind(a, b):
    try:
        return float(a) % float(b)
    except:
        return "None"


def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False


def is_reset(op):
    if op[-1] == "$":
        return True
    else:
        return False


def is_terminate(op):
    if op == "#":
        return True
    else:
        return False

def history():
  global last_calculation
  if last_calculation == []:
    print("No past calculations to show")
  else:
    for i in last_calculation:
        print(i)

def select_op(op):
    if op == " ":
        return add
    elif op == "-":
        return sub
    elif op == "*":
        return mul
    elif op == "/":
        return div
    elif op == "^":
        return power
    elif op == "%":
        return remind
    else:
        raise Exception("Invalid operator")


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    : $ ")
  print("8.History  : ? ")

  # take input from the user

  choice = input("Enter choice( ,-,*,/,^,%,#,$,?): ")
  print(choice)
  try:
      if (choice in "? -*/^%#$"):
          if is_reset(choice):
              continue
          elif is_terminate(choice):
              print("Done. Terminating")
              break
          elif (choice == "?"):
              history()
              continue
          else:
              num1 = input("Enter first number: ")
              print(num1)
              if (is_reset(num1)):
                  continue
              if (is_terminate(num1)):
                  print("Done. Terminating...")
                  exit()
              if (is_number(num1)):
                  num1 = float(num1)
              else:
                  print("Not a valid number,please enter again")
                  continue

          num2 = input("Enter second number: ")
          print(num2)

          if (is_reset(num2)):
              continue

          if (is_terminate(num2)):
              print("Done. Terminating")
              exit()

          if (is_number(num2)):
              num2 = float(num2)

          else:
              print("Not a valid number,please enter again")
              continue

          print(num1, str(choice), num2, "=", select_op(choice)(int(num1), int(num2)))
          lastCalculation = "{0} {1} {2} = {3}".format(num1, choice, num2, select_op(choice)(int(num1), int(num2)))
          last_calculation.append(lastCalculation)


      else:
          print("Invalid choice")


  except Exception as e:
      print("Something Went Wrong")
      print(e)
      continue

CodePudding user response:

In your code, you are doing the same calculation twice, which leads to duplicate error messages.

print(num1, str(choice), num2, "=", select_op(choice)(int(num1), int(num2)))
lastCalculation = "{0} {1} {2} = {3}".format(num1, choice, num2, select_op(choice)(int(num1), int(num2)))

You can instead calculate the expression once, and then use it afterwards:

result = select_op(choice)(int(num1), int(num2))
print(num1, str(choice), num2, "=", result)
lastCalculation = "{0} {1} {2} = {3}".format(num1, choice, num2, result)
  • Related