Change those eval() to float() s. eval() executes any code it passes, so your user may type something malicious there.
Now, use this for the second part:
oldGuess = n / 2.0 newGuess = ((n / oldGuess) + oldGuess) / 2.0 while (abs(oldGuess - newGuess) > 1e-06): oldGuess, newGuess = newGuess, ((n / oldGuess) + oldGuess) / 2.0 print("Guess: " + str(n)) print("My root: " + str(newGuess)) print("Accuracy: " + str(newGuess - (n**0.5)))
This comma syntax is a Python idiom, useful for replacing values unnecessarily:
temp = new new = old * something old = temp
Your condition for the while loop tends to end the loop when your difference is less than this (very small) value. This way, you will loop until it is bigger.
Note. You can also use math.sqrt(n) instead of n ** 0.5 . You need import math .
If you want to see what your program does, try print to enter the values of oldGuess and newGuess in a while . You will see how this will change them until you come to an answer.
Edit
I notice that you seem to have stumbled over why you should do oldGuess = newGuess . Let me explain: the = operator does not match the equal sign in mathematics. The equal sign says that the thing on the left is the same as the thing on the right; that is, they are equivalent. In Python, the = operator says: "Give the left side the same value as the thing on the right." It is called an assignment operator. You are thinking of the == operator, which checks for equivalence (mostly).
>>> a = 10 >>> b = 4 >>> b = a >>> b 10 >>> a == b True >>> c = 6 >>> b = c >>> b 6 >>> a == b False >>> b == c True >>> a == c False >>> a,b,c (10, 6, 6)
As you can see, when you use the = operator, you do not bind these variables together, saying that they are now one and the same. If you set b = a and then set b = c , b == a will become false, because b no longer has the same value as a . a also does not change, because b its value was assigned, and not vice versa. Think about what instead of the = operator it looks like <- (I think some languages actually use this as an assignment operator).
Why does it matter? Well, you assign something new to a variable, you forget the old value. If you do not have another variable storing the same value, it is lost forever. Your job is to update oldGuess to the previous newGuess . In other words, if your guesses were "a", "b", "c", "d", you start with oldGuess as "a" and from there calculate newGuess as "b". Since this obviously was not the right guess, you say that oldGuess now what only newGuess was - “b”, and you newGuess next newGuess , which is “c”.
You need the oldGuess value to calculate the newGuess value. But you need the newGuess value (before the change) to update the oldGuess value. This is catch-22 unless you save the previous value of newGuess , as I showed above (as an example of swap). That is why you need it.