pythonpython-3.xvariablesinputcalculator

How to store a variable and use it afterwards in a calculator?


Here's my code:

cont = "Y"
greeting = print("Hi, welcome to the calculator. What is your calculation?: ")


num1 = float(input("What is the first number you would like to use? "))
op = input("Select operation: (+, -, /, *, **) ")
num2 = float(input("What is the second number you would like to use? "))

if op == '+':
    x = num1 + num2
    print (x)
elif op == '-':
    x = num1 - num2
    print(x)
elif op == '/':
    x = num1 / num2
    print(x)
elif op == '*':
    x = num1 * num2
    print(x)
elif op == '**':
    x = num1 ** num2
    print(x)
else:
    print("error")
    pass


cont = input("Would you like to use another term? (Y/N): ")

while cont == "Y":
   op1 = input("Select operation: (+, -, /, *, **)")
   num = float(input(("Input the next number: ")))
   if op1 == '+':
        y = x + num
        print (y)
        cont = input("Would you like to continue? (Y/N): ")
   elif op1 == '-':
        z = x - num
        print(z)
        cont = input("Would you like to continue? (Y/N): ")
   elif op1 == '/':
        div = x / num
        print(div)
        cont = input("Would you like to continue? (Y/N): ")
   elif op1 == '*':
        mult = x * num
        print(mult)
        cont = input("Would you like to continue? (Y/N): ")
   elif op1 == '**':
        car = (x ** num)
        print(car)
        cont = input("Would you like to continue? (Y/N): ")


   else:
        print("error")
        pass
    
else:
       print("Finished")

Basically, it work's when adding num1 and num2, it works again one more time since it uses x and the new number(num) along with a new operator. However, the problem occurs when continuing AGAIN, as the program uses x instead of the new number(y/z/div/mult/car).

Sorry if this is phrased bad(I'm new), but basically I want it to use the new variable after selecting continue twice, but I don't know how to.


Solution

  • You can re-use the same variable. Instead of writing y/z/div/mult/car = ..., you can replace all of the with x = ....