[Tutor] exercise (while loop)

Dave Angel davea at davea.name
Tue Apr 1 11:51:48 CEST 2014


 Scott W Dunning <scott.w.d at cox.net> Wrote in message:
> 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
> 

Without an initial value for x, this should give an immediate
 exception.   Assuming you fix that as below,  you now have the
 problem that they never change x, so if it isn't right on first
 loop, it never will be. Next you have the problem of inconsistent
 spelling of eps. And final thing I notice is that it doesn't
 return a value.  Once you remove the debug print in the function,
  there's no way to see the result. 


> round(square_root(9))
> 
> I tweaked

Good job, you fixed most of the bugs. 

> 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.

Sure it is, you're just not printing it. You forgot to save the
 result of rounding,  and forgot to print the saved
 value.



-- 
DaveA



More information about the Tutor mailing list