-1

I wrote this simple calculator program to ask for two numbers and then perform a certain action on them like dividing the first by the second etc. I implemented it in a big while loop that is repeated if the user chooses to repeat it after a calculation. However, after the user enters the operation they want to perform the program does not give the answer but asks the user if they want to repeat. What did I do wrong?

import random, time

valid_operations = ("/", "*", "+", "-")
valid = 3
repeat = "y"

while repeat == "y":
    number_1 = input('Enter first number \n')
    if number_1.isdigit() == True:
        num_1 = number_1

    else:
        print("that is not a valid integer")
        exit()

    number_2 = input('Enter second number \n')

    if number_2.isdigit() == True:
        num_2 = number_2

    else:
        print("that is not a valid integer")
        exit()

    operation = input("what operation would you like? \nvalid operations include:\n/ - divide\n* - multiply\n+ - add\n- - subtract\n")

    while valid > 0:
        if operation in valid_operations:
            if operation == "/":
                print(f"Answer = {int(num_1) / int(num_2)}")
                valid -= 3

            elif operation == "*":
                print(f"Answer = {int(num_1) * int(num_2)}")
                valid -= 3

            elif operation == "+":
                print(f"Answer = {int(num_1) + int(num_2)}")
                valid -= 3
                
            elif operation == "-":
                print(f"Answer = {int(num_1) - int(num_2)}")
                valid -= 3

        else:
            print(f"that is not a valid operation you have {valid} more attmepts to type a valid operation")
            valid -= 1
    
    time.sleep(2)

    want_rep = input("would you like to do another calculation? y/n\n")
    if want_rep == "y":
        repeat = "y"
    elif want_rep == "n":
        repeat = "n"
    else:
        print("that is not a valid response, please choose either yes - y or no - n")


exit()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jstEagle
  • 1
  • 1
  • your should not use `exit()`, instead use `break` if you want to stop iterating – Sembei Norimaki Nov 23 '22 at 15:32
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Thomas Weller Nov 23 '22 at 15:32

1 Answers1

0

Problem lies in the valid variable. You define it as 3 before the first iteration. Then, inside the second while loop, it is reduced to 0 by
valid -= 3
And you never restore the starting value. So, the program comes back to the operation input, reads the loop condition:
while valid > 0:
And omits it, as valid equals 0.

Ni3dzwi3dz
  • 177
  • 8