pythoncalculator

Python Calculator Code


I'm fairly new to python and have tried to develop a calculator. I have created it so that it keeps asking you questions until you press 9 and exits. I have made an error while doing this and it keeps asking me to enter first number and keeps looping that

loop = 1
oper = 0

while loop == 1:    
    num1 = input("Enter the first number: ")
    print num1

    oper = input("+, -, *, /,9: ")
    print oper

    num2 = input("Enter the second number: ")
    print num2

    if oper == "+":
        result = int(num1) + int(num2)
    elif oper == "-":
        result = int(num1) - int(num2)
    elif oper == "*":
        result = int(num1) * int(num2)
    elif oper == "/":
        result = int(num1) / int(num2)
    elif oper == "9":
        loop = 0


    print "The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result)

    input("\nPress 9 to exit.")

Solution

  • You had problem with indentation and here's a better way to exit using break for the while loop:

    loop = 1
    oper = 0
    
    while loop == 1:
    
        x = input("Press 9 to exit otherwise anything to continue:")#much better way
        if x == "9":
            break
        num1 = input("Enter the first number: ")
        print (num1)
    
        oper = input("+, -, *, /: ")
        print (oper)
    
        num2 = input("Enter the second number: ")
        print (num2)
    
        if oper == "+":
            result = int(num1) + int(num2)
        elif oper == "-":
            result = int(num1) - int(num2)
        elif oper == "*":
            result = int(num1) * int(num2)
        elif oper == "/":
            result = int(num1) / int(num2):
        else:
           print("Invalid operator!") #if user inputs something else other than those
    
    
        print ("The result of " + str(num1) + str(oper) + str(num2) + " is " + str(result))