Calculator Help

# Add, Subtract, Multply, Divide with Functions

# Add Function
def add():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 + num2

        return answer

# Subtract Function
def subtract():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 - num2

        return answer

# Multiply Function
def multiply():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 * num2

        return answer

# Divide Function
def divide():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 / num2

        return answer

# Main
print("---------------")
print("|             |")
print("|1. ADD       |")
print("|2. Subtract  |")
print("|3. Multiply  |")
print("|4. Divide    |")
print("|             |")
print("---------------")

# Choice Variable
choice = int(input("Please choose a number (1-4): "))

# Choice Loop
if (choice == 1):
       print("\nThe answer is: ", add())
elif (choice == 2):
       print("\nThe answer is: ", subtract())
elif (choice == 3):
       print("\nThe answer is: ", multiply())
elif (choice == 4):
       print("\nThe answer is: ", divide())
       
       if (choice != '1', '2', '3', '4'):
              print("\nError: Invalid Number, Restart and Try Again.")
              continue

# Check If User Wants Another Calculation
       nextcalc = input("Do you want to do another calculation (yes/no): ")

       if nextcalc == "no":
               break
else:
       print("Program Ending..")

I am trying to get it so when done it asks the user if they want to do another calculation and if yes then to ask what type of calculation and then numbers input, and if no then end the program. Also if anything besides 1-4 is entered I want it to ask the user again for their choice.

For this, you will need a loop. I would suggest a while loop. You can see a little example and a description here: 3. An Informal Introduction to Python — Python 3.12.0 documentation

Other than that, it looks to me like your script has all the other pieces it needs. It just needs a little reorganization to use a loop. :slightly_smiling_face:

Ok. Thank you, i was thinking about a while loop but wasn’t sure, when i do it i would have to put everything from the choice selection in it right?

Well everything from the choice loop i mean

This:

if (choice != '1', '2', '3', '4'):

is treated as true because the condition is a non-empty tuple - basically ((choice != '1'), '2', '3', '4').

What you want is if choice not in {'1', '2', '3', '4'}:.

Ok I see, im use to c++, so getting use to python again.

# Add, Subtract, Multply, Divide with Functions

# Add Function
def add():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 + num2

        return answer

# Subtract Function
def subtract():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 - num2

        return answer

# Multiply Function
def multiply():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 * num2

        return answer

# Divide Function
def divide():
        num1 = int(input("\nEnter 1st Number: "))
        num2 = int(input("Enter 2nd Number: "))

        answer = num1 / num2

        return answer

# Main
print("\n")
print("---------------")
print("|             |")
print("|1. ADD       |")
print("|2. Subtract  |")
print("|3. Multiply  |")
print("|4. Divide    |")
print("|             |")
print("---------------")

# Choice Variable
#choice = int(input("Please choose a number (1-4): "))

# Choice Loop 
while True:
       choice = int(input("Please choose a number (1-4): "))

       if (choice == 1):
              print("The answer is ", add())
       elif (choice == 2):
              print("The answer is ", subtract())
       elif (choice == 3):
              print("The answer is ", multiply())
       elif (choice == 4):
              print("The answer is ", divide())
#  (choice !=) statment can also use
       elif choice not in {'1', '2', '3', '4'}:
       #elif (choice != '1', '2', '3', '4'):
              print("\nError: Invalid Number, Try Again.")
              continue

# Check If User Wants Another Calculation
       nextcalc = input("\nDo you want to do another calculation (yes/no): ")

       if nextcalc == "no":
	       print("Program Ending..")
	       break
       else:
               print("\n1. Add \n2. Subtract \n3. Multiply \n4. Divide")
               continue


This is my new code, all of it works even the alternate way for the choice not in and choice !=, everything works like exactly like it should, however I feel like there might be better ways to organize the code, but any ideas would be great for organization.

Thanks you for the advice and help @flyinghyrax @MRAB

Looks nice! Good work. :slightly_smiling_face:

If you want to experiment with how the code is organized[1], there are 2 things I would try:

  1. There are some places where code is repeated. If you find you have repeated the same lines of code 3+ times with only a small change, that code is a good candidate to put in its own function. (And the difference between the repetitions, if any, becomes the function’s arguments!)
  2. There is a way to use a dict to replace most of your if..elif cases that check the choice inside the while loop. It works by using the choices as keys and the functions as arguments. The pattern has more than one name, but I’ve heard it called a “dispatch table”. I think they’re kind of fun.

  1. if you want to sound fancy, we sometimes call this “refactoring” :wink: ↩︎

Ok i will look at it and try to organize it with the ways you suggested

Just for some inspiration, here’s a minimal example of how you might restructure your code to behave the same but in fully 5x fewer lines of code (16 vs 80). It achieves this by:

  • Inlining or eliminating a large amount of duplicate and redundant code
  • Replacing hand-written functions with the built-in operators from the operator module, which is both simpler and more efficient
  • Uses a dispatch table (via a dictionary lookup) instead of a manual chain of if statements

Notably, this is all possible without even using functions (which I’d recommend in any real code), nor more intermediate constructs like list comprehensions, f-strings or star unpacking.

from operator import add, sub, mul, truediv

OPERATIONS = {1: add, 2: sub, 3: mul, 4: truediv}

while True:
    print("\n1. Add \n2. Subtract \n3. Multiply \n4. Divide")
    choice = int(input("Please choose a number (1-4): "))
    if choice not in {1, 2, 3, 4}:
        print("\nError: Invalid Number, Try Again.")
        continue
    num1 = int(input("Enter 1st Number: "))
    num2 = int(input("Enter 2nd Number: "))
    print("The answer is ", OPERATIONS[choice](num1, num2))

    if input("\nDo you want to do another calculation (yes/no): ") == "no":
        print("Program Ending...")
        break

To save one more line and some duplication, you could also replace the nearly-duplicate lines getting the two numbers:

    num1 = int(input("Enter 1st Number: "))
    num2 = int(input("Enter 2nd Number: "))
    print("The answer is ", OPERATIONS[choice](num1, num2))

with a list comphrension asking for both numbers via an f-string, and then use the star operator to unpack that into the mathematical function:

    numbers = [int(input(f"Enter number {i + 1}: ")) for i in range(2)]
    print("The answer is ", OPERATIONS[choice](*numbers))

However, the savings is relatively modest relative to the cognitive complexity and additional concepts it required, so I avoided it above.

1 Like