 # While loop

e=1
y=24.0
g=y/2.0
ng=0
while abs(gg - y)>=e:
ng+=1
g=g-(((g**2)-y)/(2
g))
print(g,ng)

I haven’t understood why the value of g is changing in a while loop? Please, elaborate on it .

It will aid troubleshooting if you format your code inside the preformatted text tool – `</>`.

2 Likes

like @harrjt said, this is hard to interpret without proper formatting.

``````while abs(gg - y)>=e: # gg is not a variable that you declare in the code shown, did you mean g*g
ng+=1
g=g-(((g**2)-y)/(2g)) # this code changes the value of g
``````

While loops run as long as their condition is `== True`. They will continue to run all their code in loops until that is the case. If the code is as I pasted (and by `gg` you meant `g*g`), then every time `g=g-(((g**2)-y)/(2g))` happens, `g` will change by `g-(((g**2)-y)/(2g))`.

As a side note `g-(((g**2)-y)/(2g))` can be simply written as `g - ( (g**2 - y) / 2g )`. Not only do you spare a set of parentheses (remember, we are running out of them in the world! this is a joke), but your code becomes more legible for yourself, and future collaborators.

3 Likes