# 牛顿近似平方根的方法

Jianna

``````import math

def newton(x):
tolerance = 0.000001
estimate = 1.0
while True:
estimate = (estimate + x / estimate) / 2
difference = abs(x - estimate ** 2)
if difference <= tolerance:
break
return estimate

def main():
while True:
x = input("Enter a positive number or enter/return to quit: ")
if x == '':
break
x = float(x)
print("The program's estimate is", newton(x))
print("Python's estimate is     ", math.sqrt(x))
main()
``````

``````x = input("Enter a positive number or enter/return to quit: ")
if not x:
break
x = float(x)
``````

This should avoid the `EOFError`.

### Edit

If you want to use a blank input (hitting the return line) to break out of the loop, you can try this alternative syntax:

``````x = input("Enter a positive number or enter/return to quit: ")
if not x:
break
x = float(x)
``````

The `not x` checks if `x` is blank. It is also more pythonic than `x == ""`. Additional methods to detect a blank input are in this post as well: How do you get Python to detect for no input.

0 条评论