[Tutor] exercise (while loop)

Scott W Dunning scott.w.d at cox.net
Tue Apr 1 03:07:52 CEST 2014


I’m working on a few exercises and I’m a little stuck on this one.  

This is what the book has but it just gives me an endless loop.

def square_root(a, eps=1e-6):
	while True:
		print x
   		y = (x + a/x) / 2
   		if abs(y-x) < epsilon:
			break

round(square_root(9))

I tweaked it to what I thought was correct but when I test it I get nothing back.

def square_root(a, eps=1e-6):
   x = a/2.0
   while True:
       y = (x + a/x)/2.0
       if abs(x - y) < eps:
           return y
       x = y

round(square_root(9))

The way I tweaked it seems to work, I’m getting the correct answer on the calculator but the interpreter is not returning anything when I check in python.

The books way is just print whatever I use for x, so I don’t understand that at all.




More information about the Tutor mailing list