mardi 18 septembre 2018

How can an if code block continue from where while loop left off in such cases?

I don't have any experience with coding at all and I have just started learning Python.

In John Guttag's book "Introduction to Computation and Programming Using Python With Application to Understanding Data", at the beginning of chapter 3, there is a code example:

#Find the cube root of a perfect cube
x = int(input('Enter an integer: '))
ans = 0
while ans**3 < abs(x):
    ans = ans + 1
if ans**3 != abs(x):
    print(x, 'is not a perfect cube')
else:
    if x < 0:
        ans = -ans
    print('Cube root of ' + str(x) + ' is ' + str(ans))

What I have a hard time understanding is how "if" outside of "while" can pick up from where the loop left off with the iteration? If it is because of the last iteration of ans which gets it out of the loop and also satisfies the if condition, how does the if condition work for the values of ans and thus x inside the loop?(ans^3 is not equal to x only inside the while loop, how come can this part work:

 if ans**3 != abs(x):
     print(x, 'is not a perfect cube')

I really don't know how else to ask this but this is the code that I came up with before I peeked at the code in the book, it worked, and maybe it wil help to clarify what I am exactly asking:

x=int(input('Enter an integer: '))
crx=0

while True:
    if crx**3<abs(x):
        crx=crx+1
    elif crx**3==x:
        print('The cube root of',x,'is',str(crx)+'.')
        break
    elif crx**3==-x:
        print('The cube root of',x,'is',str(-crx)+'.')
        break
    else:
        print(x,'is not a perfect cube.')
        break

In my mind, somehow, I had to insert the if code blocks inside the while loop...

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire