Reputation: 61
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!
Upvotes: 2
Views: 865
Reputation: 7006
You convert the operator to upper case but the elif has lower case 'sqrt'.
Change it to
elif (operator) == "SQRT":
result = math.sqrt(no1)
Upvotes: 2
Reputation: 10979
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.
Upvotes: 1