SHARE
TWEET

Untitled

a guest Oct 21st, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def newton(): #No parameter needed if the user is going to supply one
  2.    
  3.    
  4.     # Can intiialize tolerance outside of the loop since its value never changes
  5.     tolerance = 0.000001
  6.  
  7. #Give user square root for every number they enter.
  8.     while True:
  9.         # Get input from user
  10.         g = input("Type a number to compute square root, or press enter to close: ")
  11.        
  12.         # If user presses enter, exit the program
  13.         if g == "":
  14.             break
  15.        
  16.         # --Reprompting user if they give erroneous input--
  17.        
  18.         # The 'try' statement is super useful. It basically tells Python to try to do
  19.         # something, and if that something would give an error,
  20.         # then execute the 'except' statement. If however no errors are raised,
  21.         # then just skip to the 'else' statement and keep going
  22.        
  23.         # Hey Python, try to convert the user's input to a float
  24.         try:
  25.             g = float(g)
  26.            
  27.         # If and only if doing the 'try' statement gives an error (e.g. the user gave a string),
  28.         # then execute my 'except' statement. The 'else' statement gets disregarded.
  29.         except:
  30.             print("Sorry, that is not a number.")
  31.            
  32.         # If and only if there is no need to execute the 'except' statement
  33.         # (i.e. no errors were raised when you did the 'try' statement),
  34.         # then execute my 'else' statement
  35.         else:  
  36.             estimate = g
  37.  
  38.             #loop that uses Newtons square root approximation algorithm and prints it
  39.  
  40.             while True:
  41.  
  42.                 estimate = (estimate + g / estimate) / 2
  43.                 difference = abs(g-estimate ** 2)
  44.  
  45.                 if difference <= tolerance:
  46.                     break
  47.  
  48.             print(estimate)
  49.  
  50.  
  51.         # The last few lines of the code you had are not needed as the user
  52.         # will always get reprompted as to if they want to end the program
  53.  
  54.  
  55. newton()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top