1

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')

Code Image

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.)

4
  • 2
    while will keep iterate as long as ans*ans < x then executing ans = ans +1, it will break if ans*ans >= x, and continue to if statement below it, which is if ans*ans != x: Commented Oct 21, 2020 at 3:27
  • if and else on line 6 and 8 has no relationship with while on line 4 Commented Oct 21, 2020 at 3:35
  • does it keep iterating that over and over and THEN checks the if statement? yes, as long as ans*ans < x Commented Oct 21, 2020 at 3:37
  • It helps to convert things like else: 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. Commented Oct 21, 2020 at 4:19

2 Answers 2

1

Since the if ans*ans < x: is not inside the while loop, the while loop keeps iterating until ans*ans < 4.5, and then it checks the if statement. It doesn't check the if ans*ans != x: each time the while loop iterates.

Sign up to request clarification or add additional context in comments.

1 Comment

Got it-- thank you. If and else are only checked after the while loop breaks. And I guess the if and else do cover the only options for potential answers.
0

trace can help visual program flow. Since there aren't too many step here, you can show each line executed then go back to the source to compare.

$ python3 -m trace --trace test.py
 --- modulename: test, funcname: <module>
test.py(1): x = 4.5
test.py(2): ans = 0
test.py(3): if x>= 0:
test.py(4):     while ans*ans < x:
test.py(5):         ans = ans +1
test.py(4):     while ans*ans < x:
test.py(5):         ans = ans +1
test.py(4):     while ans*ans < x:
test.py(5):         ans = ans +1
test.py(4):     while ans*ans < x:
test.py(6):     if ans*ans != x:
test.py(7):         print (x, 'is not a perfect square')
4.5 is not a perfect square

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.