Python calculator with the math.sqrt function

823 views Asked by At

I am very new to Python but I wanted to code an calculator. It works fine exept for the sqrt function. Everytime I try to calculate the square root of a number I get the error message. I know that there are probably thousand ways to code a better calculator but I would really like to know what I did wrong and how I can fix this. This is my code:

import math

no1 = float(input('Insert a number: '))
operator = input("Operator: ").upper()
result = no1

while operator != "=":
    if (operator) == "-":
        no2 = float(input('Insert next number: '))
        result = result - no2
        operator = input("Operator: ").upper()
    elif (operator) == "/":
        no2 = float(input('Insert next number: '))
        result = result / no2
        operator = input("Operator: ").upper()
    elif (operator) == "+":
        no2 = float(input('Insert next number: '))
        result = result + no2
        operator = input("Operator: ").upper()
    elif (operator) == "*":
        no2 = float(input('Insert next number: '))
        result = result * no2
        operator = input("Operator: ").upper()
    elif (operator) == "^":
        no2 = float(input('Insert next number: '))
        result = math.pow(result,no2)
        operator = input("Operator: ").upper()
    elif (operator) == "sqrt":
        result = math.sqrt(no1)
    else:
        print('Error!')
        operator = "="

print(result)

Thank you very much!

2

There are 2 answers

1
scotty3785 On BEST ANSWER

You convert the operator to upper case but the elif has lower case 'sqrt'.

Change it to

elif (operator) == "SQRT":
    result = math.sqrt(no1)
0
Peter Collingridge On

You are converting the input to a uppercase, but then testing for 'sqrt'. Test for 'SQRT' instead. You will also want to remove the while loop otherwise it will never exit.