Python: While loop not running as expected

Question:

I am new to python and am trying to make a calculator. I have +, -, *, / and raising to the power of x done and am trying to do have a function that finds the square root of a number.
I had a version working but it only worked if there was a number that was exactly the square root. As in 3 is exactly the square root of 9 but if the square root had a decimal such as the square root of 6.5 it would crash. I wanted it to be able to do the float numbers as well. The way I was doing it originally was:

tempAns = 1
while tempAns <= num1:
    if tempAns * tempAns == num1:
        answer = tempAns
        break

    tempAns += 1

print('The answer is: ' + str(answer))

But my problem was that as I was incrementing it by 1 it was missing the numbers in between. I tried to increment it by 0.1 each time with:

tempAns = 0.1
while tempAns <= num1:
    if tempAns * tempAns == num1:
        answer = tempAns
        break

    tempAns += 0.1

print('The answer is: ' + str(answer))

But this just gave me an error saying: UnboundLocalError: local variable 'answer' referenced before assignment

I have absolutely no idea why this is happening as it should be looping until it assigns a number to 'answer'.

Any help will be appreciated!
Also any suggestions on how to make my code cleaner would be nice as I’m new to python.
Thanks in advance!

Asked By: iamdeedz

||

Answers:

sqrt() function is an inbuilt function in Python programming language that returns the square root of any number.

Syntax:
math.sqrt(x)

Parameter:
x is any number such that x>=0

Returns:
It returns the square root of the number
passed in the parameter.

Answered By: Ahmed_Aboutalib
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.