简体   繁体   English

(已解决)Python:While 循环未按预期运行

[英](SOLVED) Python: While loop not running as expected

I am new to python and am trying to make a calculator.我是 python 的新手,正在尝试制作一个计算器。 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.我已经完成 +、-、*、/ 并提高到 x 的幂,并且正在尝试做一个 function 来找到数字的平方根。 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.正如 3 恰好是 9 的平方根,但如果平方根有一个小数,例如 6.5 的平方根,它就会崩溃。 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.但我的问题是,当我将它递增 1 时,它丢失了中间的数字。 I tried to increment it by 0.1 each time with:我尝试每次将它增加 0.1:

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但这只是给了我一个错误提示: 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' .我完全不知道为什么会这样,因为它应该循环播放,直到它为'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.此外,任何关于如何使我的代码更清晰的建议都会很好,因为我是 python 的新手。 Thanks in advance!提前致谢!

sqrt() function is an inbuilt function in Python programming language that returns the square root of any number . sqrt() function 是 Python 编程语言中内置的 function ,它返回任何数字的平方根

Syntax: math.sqrt(x)语法:math.sqrt(x)

Parameter: x is any number such that x>=0参数:x 是满足 x>=0 的任何数字

Returns: It returns the square root of the number passed in the parameter.返回:它返回参数中传递的数字的平方根。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM