'Return to main menu function for python calculator program

I was asked to write a calculator in Python, and I completed it, but there is only one issue that needs to be fixed.

What is the prerequisite? "Once the user inputs/selects an arithmetic operation, the program should ask the user to enter the two operands one by one, separated by Enter key. If the user made a mistake while entering the parameters, he can return to main menu by pressing ‘$’ key at the end of the input string, followed by the Enter key.

I'll give you the code I wrote here, and I'd appreciate it if you could make this to get the return function.

def Add(a, b):
    return a + b
  
# Function to subtract two numbers 
def Subtract(a, b):
    return a - b
  
# Function to multiply two numbers
def Multiply(a, b):
    return a * b
  
# Function to divide two numbers
def Divide(a, b):
    return a / b

# Function to power two numbers
def Power(a, b):
    return a ** b

# Function to remaind two numbers
def Remainder(a, b):
    return a % b

def Reset(a,b):
    return print(choice)


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 ('+', '-', '*', '/', '^', '%', '#', '$'):
      if choice == '#':
          print("Done. Terminating")
          break
      a = input('Enter first number: ')
      print(str(a))
      b = input('Enter second number: ')
      print(str(b))

      
  if choice == '+':
      print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))
  elif choice == '-':
      print(float(a), "-",float(b), "=", Subtract(float(a), float(b)))
  elif choice == '*':
      print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))
  elif choice == '/':
      if int(b) != 0:
          print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
          break
      else:
          print("float division by zero")
          print(float(a), "/", float(b), "=", "None")
  elif choice == '^':
      print(float(a), "**",float(b), "=", Power(float(a), float(b)))
  elif choice == '%':
      print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))
      break
      

  else:
      print('Not a valid number,please enter again.')
      ```


Solution 1:[1]

This kind of task is best (IMHO) handled in a so-called "table driven" manner. In other words, you create a table (in this case a dictionary) that has all the options built into it. Your core code then becomes much easier and the functionality is more extensible because all you need to do is add to or take away from the dictionary.

This structure also demonstrates how the user can be prompted for more input if/when something goes wrong.

def Add(a, b):
    return a + b

def Subtract(a, b):
    return a - b

def Multiply(a, b):
    return a * b

def Divide(a, b):
    return a / b

def Power(a, b):
    return a ** b

def Remainder(a, b):
    return a % b

options = {'+': ('Add', Add, '+'),
           '-': ('Subtract', Subtract, '-'),
           '*': ('Multiply', Multiply, '*'),
           '/': ('Divide', Divide, '/'),
           '^': ('Power', Power, '**'),
           '%': ('Remainder', Remainder, '%'),
           '#': ('Terminate', None)}

while True:
    print('Select operation: ')
    for i, (k, v) in enumerate(options.items(), 1):
        print(f'{i}. {v[0]:<10}: {k} : ')
    option = input(f'Enter choice ({",".join(options.keys())}) : ')
    if control := options.get(option):
        _, func, *disp = control
        if not func:
            break
        a = input('Enter first number: ')
        b = input('Enter second number: ')
        try:
            a = float(a)
            b = float(b)
            print(f'{a} {disp} {b} = {func(a, b)}')
        except (ValueError, ZeroDivisionError) as e:
            print(e)
    else:
        print('Invalid option!')

Solution 2:[2]

Thank you so much for all your responses. With your help I was able to come to a decisive conclusion very quickly.

This is the end result I got after the changes I made:

def Add(a, b):
    return a + b
  
# Function to subtract two numbers 
def Subtract(a, b):
    return a - b
  
# Function to multiply two numbers
def Multiply(a, b):
    return a * b
  
# Function to divide two numbers
def Divide(a, b):
    return a / b

# Function to power two numbers
def Power(a, b):
    return a ** b

# Function to remaind two numbers
def Remainder(a, b):
    return a % b


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 ('+', '-', '*', '/', '^', '%', '#', '$'):
      if choice == '#':
          print("Done. Terminating")
          break
      a = input('Enter first number: ')
      print(str(a))
      if a.endswith('$'): continue
      b = input('Enter second number: ')
      print(str(b))
      if b.endswith('#'):
        print("Done. Terminating")
        break
      if b.endswith('$'): continue

      
      


      
  if choice == '+':
      print(float(a), "+" ,float(b), "=", Add(float(a), float(b)))
  elif choice == '-':
      print(a, "-", b, "=", Subtract(a, b))
  elif choice == '*':
      print(float(a), "*",float(b), "=", Multiply(float(a), float(b)))
  elif choice == '/':
      if int(b) != 0:
          print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
          break
      else:
          print("float division by zero")
          print(float(a), "/", float(b), "=", "None")
  elif choice == '^':
      print(float(a), "**",float(b), "=", Power(float(a), float(b)))
  elif choice == '%':
      print(float(a), "%",float(b), "=", Remainder(float(a), float(b)))
      break
      

  else:
      print('Not a valid number,please enter again.')
      ```

Solution 3:[3]

I think I found a way to do this.

You want to loop back to the menu where you ask to choose among math symbols. You can add a while based on a variable (bool) set to True.

You then get two while loops.

reset = True

while reset:
    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    : $ ")

Therefor if you spot any "$"in either a, b or your choice you can just break. You will come out of the second while loop and go back to the first one, printing the menu again.

But then you have to modify the behaviour when you encounter "#" because breaking now brings you back to the top and doesn't exit the program. You first have to set reset to reset = False then you can break, therefore exiting both loops.

            if choice == '#':
                print("Done. Terminating")
                reset = False
                break
            if '$' in a or '$' in b or '$' in choice :
                print("Resetting.")
                break

You can learn more about nested while loops here : https://code4coding.com/nested-while-loop-in-python/

To add clarity to you code you might want to get rid of all your functions since python have already builtin functions done with the corresponding math symbol ^^

EDIT : FULL SNIPPET

reset = True

while reset:
    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 ('+', '-', '*', '/', '^', '%', '#', '$'):
            if '$' == choice :
                print("Resetting.")
                break
            if choice == '#':
                print("Done. Terminating")
                reset = False
                break
            a = input('Enter first number: ')
            print(str(a))
            if '$' in a :
                print("Resetting.")
                break
            b = input('Enter second number: ')
            print(str(b))
            if '$' in a or '$' in b :
                print("Resetting.")
                break


        if choice == '+':
            print(float(a), "+", float(b), "=", Add(float(a), float(b)))
        elif choice == '-':
            print(float(a), "-", float(b), "=", Subtract(float(a), float(b)))
        elif choice == '*':
            print(float(a), "*", float(b), "=", Multiply(float(a), float(b)))
        elif choice == '/':
            if int(b) != 0:
                print(float(a), "/", float(b), "=", Divide(float(a), float(b)))
                break
            else:
                print("float division by zero")
                print(float(a), "/", float(b), "=", "None")
        elif choice == '^':
            print(float(a), "**", float(b), "=", Power(float(a), float(b)))
        elif choice == '%':
            print(float(a), "%", float(b), "=", Remainder(float(a), float(b)))
            break


        else:
            print('Not a valid number,please enter again.')

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 Albert Winestein
Solution 2 Sanjeev M
Solution 3