Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def newton(): #No parameter needed if the user is going to supply one
- # Can intiialize tolerance outside of the loop since its value never changes
- tolerance = 0.000001
- #Give user square root for every number they enter.
- while True:
- # Get input from user
- g = input("Type a number to compute square root, or press enter to close: ")
- # If user presses enter, exit the program
- if g == "":
- break
- # --Reprompting user if they give erroneous input--
- # The 'try' statement is super useful. It basically tells Python to try to do
- # something, and if that something would give an error,
- # then execute the 'except' statement. If however no errors are raised,
- # then just skip to the 'else' statement and keep going
- # Hey Python, try to convert the user's input to a float
- try:
- g = float(g)
- # If and only if doing the 'try' statement gives an error (e.g. the user gave a string),
- # then execute my 'except' statement. The 'else' statement gets disregarded.
- except:
- print("Sorry, that is not a number.")
- # If and only if there is no need to execute the 'except' statement
- # (i.e. no errors were raised when you did the 'try' statement),
- # then execute my 'else' statement
- else:
- estimate = g
- #loop that uses Newtons square root approximation algorithm and prints it
- while True:
- estimate = (estimate + g / estimate) / 2
- difference = abs(g-estimate ** 2)
- if difference <= tolerance:
- break
- print(estimate)
- # The last few lines of the code you had are not needed as the user
- # will always get reprompted as to if they want to end the program
- newton()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement