Reaps777
Reaps777

Reputation: 25

Menu for python calculator

I have created a calculator in python that can calculate the addition, subtraction, multiplication, division or modulus of two integers. What equation is executed is based on which number is type in from the menu, and I would like the user to be able to go back to the menu after an equation after being asked whether or not to "continue?". Would appreciate any help

print("MENU")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulous")

menu = input("Enter your choice: ")
if int(menu) == 1:
 def additon(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
    return(number1 + number2)
answer1 = additon()
print("Result:", answer1)

if int(menu) == 2:
 def subtraction(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
    return(number1 - number2)
answer2 = subtraction()
print("Result: ", answer2)

if int(menu) == 3:
 def multiplication(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
    return(number1 * number2)
answer3 = multiplication()
print("Result: ", answer3)


if int(menu) == 4:
 def division(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
    return(number1 / number2)
answer4 = division()
print("Result: ", answer4)


if int(menu) == 5:
 def modulus(number1=int(input("Enter first number: ")), number2=int(input("Enter second number: "))):
    return(number1 % number2)
answer5 = modulus()
print("Result: ", answer5)

if int(menu) != 1 or 2 or 3 or 4 or 5:
 print("Not a valid option")

Upvotes: 2

Views: 1728

Answers (3)

Adon Bilivit
Adon Bilivit

Reputation: 27201

An answer has already been accepted for this but I'll throw this out there anyway.

This kind of exercise is ideally suited to a table-driven approach.

The operations are trivial so rather than define discrete functions a lambda will suffice

Define a dictionary where we look up and validate the user's option.

Get the user input and carry out sanity checks.

We end up with just 2 conditional checks - one of which is merely concerned with quitting the [potentially] infinite loop.

CONTROL = {'1': lambda x, y: x + y,
           '2': lambda x, y: x - y,
           '3': lambda x, y: x * y,
           '4': lambda x, y: x / y,
           '5': lambda x, y: x % y}

while True:
    print("MENU")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Modulus")
    option = input('Select an option or q to quit: ')
    if option and option in 'qQ':
        break
    if option in CONTROL:
        x = input('Input X: ')
        y = input('Input Y: ')
        try:
            result = CONTROL[option](int(x), int(y))
            print(f'Result={result}')
        except ValueError:
            print('Integer values only please')
        except ZeroDivisionError:
            print("Can't divide by zero")
    else:
        print('Invalid option')
    print()

Upvotes: 0

James Francis
James Francis

Reputation: 36

Wrap your code in a while loop. The following code should work.

def additon(number1, number2):
    return (number1 + number2)

def subtraction(number1, number2):
    return(number1 - number2)

def multiplication(number1, number2):
    return(number1 * number2)

def division(number1, number2):
    return(number1 / number2)

def modulus(number1, number2):
    return(number1 % number2)

x = True
while (x):
    print("MENU")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Modulous")

    menu = input("Enter your choice: ")
    if int(menu) == 1:
        answer1 = additon(number1=int(input("Enter first number: ")),
                          number2=int(input("Enter second number: ")))
        print("Result:", answer1)

    elif int(menu) == 2:
        answer2 = subtraction(number1=int(input("Enter first number: ")),
                              number2=int(input("Enter second number: ")))
        print("Result: ", answer2)

    elif int(menu) == 3:
        answer3 = multiplication(number1=int(input("Enter first number: ")),
                                 number2=int(input("Enter second number: ")))
        print("Result: ", answer3)


    elif int(menu) == 4:
        answer4 = division(number1=int(input("Enter first number: ")),
                           number2=int(input("Enter second number: ")))
        print("Result: ", answer4)


    elif int(menu) == 5:
        answer5 = modulus(number1=int(input("Enter first number: ")),
                          number2=int(input("Enter second number: ")))
        print("Result: ", answer5)

    elif int(menu) < 1 or int(menu) > 5:
        print("Not a valid option")

    go_again = input("Would you like to go again (y/n): ")
    if (go_again.lower()=="n"):
        x = False
    else:
        continue

Upvotes: -1

quizdog
quizdog

Reputation: 662

  1. First define your functions once at the top of the program, you are currently defining functions (eg. addition) inside if statements
  2. put all your main code in a 'forever' (while True:) loop so that each time through the loop it prints out the menu, accepts input, and displays the results then returns to the top of the loop to do it all over again
  3. when you read user input, before converting it to an integer, add code to check if the user typed something like 'q' (for quit) and if they did then use break to take you out of the 'forver' loop and end the program

here's a skeleton version:

def print_menu():
    """print the menu as show in your code"""

def addition():
   """your addition function"""
   ...

def subtraction():
  """your subtraction function"""
   ...

# etc


while True:                        # 'forever' loop

    print_menu()
    resp = input("your choice? ")
    if resp == 'q':                # user wants to quit
        break                      # so break out of forever loop

    resp = int(resp)               # change your resp to an integer
    if resp == 1:
        answer = addition()
    elif resp == 2:
        answer = subtraction()
    elif resp == 3:
        answer = multiplication()   
    elif resp == 4:
        answer = division()
    else:
        print("unknown choice, try again")
        continue                           # go back to top of loop

    print("The Answer Is", answer)



         

Upvotes: 0

Related Questions