# Calculator Help

**URL:** <https://discuss.python.org/t/calculator-help/39592>\
**Category:** Python Help\
**Tags:** help\
**Created:** [November 26, 2023, 2:19am UTC](https://discuss.python.org/t/calculator-help/39592 "2023-11-26T02:19:22Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 26, 2023, 2:19am UTC](https://discuss.python.org/t/calculator-help/39592/1 "2023-11-26T02:19:23Z")

</div>

```auto
# 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.

---

<div class="post-metadata">

**Author:** ![flyinghyrax](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/flyinghyrax/32/12394_2.png) [@flyinghyrax](https://discuss.python.org/u/flyinghyrax)\
**Post date:** [November 26, 2023, 2:33am UTC](https://discuss.python.org/t/calculator-help/39592/2 "2023-11-26T02:33:42Z")

</div>

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](https://docs.python.org/3/tutorial/introduction.html)

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. 🙂

---

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 26, 2023, 2:57am UTC](https://discuss.python.org/t/calculator-help/39592/3 "2023-11-26T02:57:38Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 26, 2023, 2:58am UTC](https://discuss.python.org/t/calculator-help/39592/4 "2023-11-26T02:58:20Z")

</div>

Well everything from the choice loop i mean

---

<div class="post-metadata">

**Author:** ![MRAB](https://avatars.discourse-cdn.com/v4/letter/m/e9c0ed/32.png) [@MRAB](https://discuss.python.org/u/MRAB)\
**Post date:** [November 26, 2023, 3:13am UTC](https://discuss.python.org/t/calculator-help/39592/5 "2023-11-26T03:13:37Z")

</div>

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'}:`.

---

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 27, 2023, 12:59am UTC](https://discuss.python.org/t/calculator-help/39592/6 "2023-11-27T00:59:23Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 27, 2023, 3:42am UTC](https://discuss.python.org/t/calculator-help/39592/7 "2023-11-27T03:42:26Z")

</div>

```auto
# 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.

---

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 27, 2023, 3:43am UTC](https://discuss.python.org/t/calculator-help/39592/8 "2023-11-27T03:43:07Z")

</div>

Thanks you for the advice and help @flyinghyrax@MRAB

---

<div class="post-metadata">

**Author:** ![flyinghyrax](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/flyinghyrax/32/12394_2.png) [@flyinghyrax](https://discuss.python.org/u/flyinghyrax)\
**Post date:** [November 27, 2023, 8:33pm UTC](https://discuss.python.org/t/calculator-help/39592/9 "2023-11-27T20:33:54Z")

</div>

Looks nice! Good work. 🙂

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” 😉

---

<div class="post-metadata">

**Author:** ![Kronos](https://avatars.discourse-cdn.com/v4/letter/k/aca169/32.png) [@Kronos](https://discuss.python.org/u/Kronos)\
**Post date:** [November 29, 2023, 6:43pm UTC](https://discuss.python.org/t/calculator-help/39592/10 "2023-11-29T18:43:27Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![CAM-Gerlach](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/cam-gerlach/32/3688_2.png) [@CAM-Gerlach](https://discuss.python.org/u/CAM-Gerlach)\
**Post date:** [December 1, 2023, 12:46am UTC](https://discuss.python.org/t/calculator-help/39592/11 "2023-12-01T00:46:54Z")

</div>

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.

```python
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:

```python
    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:

```python
    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.
