Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

just playing with the scoping of the functions; there's no reason for…

… it all to be global
  • Loading branch information...
commit bf84ee809a17b24f27f78af18a3edb93c04141d1 1 parent 8f31dac
williame williame authored
Showing with 15 additions and 27 deletions.
  1. +15 −27 square_root.py
42 square_root.py
View
@@ -1,30 +1,18 @@
-from math import *
-def main():
- x = int(raw_input("Enter a number to get the square root"))
- guess = 1
- guess = improve_answer(guess,x)
- square_root(guess,x)
-
-def square_root(guess,x):
- while(not good_enough(guess,x)):
- guess = improve_answer(guess,x)
- print guess
-
-def average(a,b):
- return (a+b)/2.0
-
-def improve_answer(guess,x):
- return average(guess,x/guess)
-
-def good_enough(guess,x):
- good = abs(guess*guess-x)
- return(good<0.001)
-
+def square_root(x,guess=1):
+ def improve_answer():
+ def average(a,b):
+ return (a+b)/2.0
+ return average(guess,x/guess)
+ def good_enough():
+ good = abs(guess*guess-x)
+ return good<0.001
+ while not good_enough():
+ guess = improve_answer()
+ return guess
if __name__ == '__main__':
- main()
-
-
-
-
+ x = float(raw_input("Enter a number to get the square root: "))
+ sqrt = square_root(x)
+ print "sqrt(%f) = %f"%(x,sqrt)
+ print "sqrd(%f) = %f"%(sqrt,sqrt*sqrt)
Please sign in to comment.
Something went wrong with that request. Please try again.