I'm watching this course and at 28:25 it includes this code:
x = 4.5
ans = 0
if x>= 0:
while ans*ans < x:
ans = ans +1
if ans*ans != x:
print (x, 'is not a perfect square')
else: print (ans)
else: print (x, ' is a negative number')
I don't get the while loop-- does it keep iterating that over and over and THEN checks the if statement? Or does it check the if statement each time it iterates? I feel rather stupid!
Would appreciate some help-- I imagine if I applied myself more I'd get it-- but this stuff is very different from music and philosophy.
(Ah-- got it now-- I didn't think through the indentation. The if and else under while will only take place after the while loop breaks because they're not "inside" the while loop. I swear I get dumber every day. Or maybe it's been a long time since I've done any truly out of domain thinking.)
ans*ans < xthen executingans = ans +1, it will break ifans*ans >= x, and continue to if statement below it, which isif ans*ans != x:ifandelseon line 6 and 8 has no relationship withwhileon line 4ans*ans < xelse: print (ans)into multiple lines with indentation. It makes the flow easier to spot and is better for stepping through with a debugger. And learn a python debugger! Then you can step through the program line by lline and see what it does.