0

This is lab 1 from CS61A. I don't understand the answer.

For question 1, why is it an infinite loop? Is it because means has a value?

>>> positive = 28
>>> while positive:
...    print("positive?")
...    positive -= 3
______

For question 2, why the program end after it printed -12, -9, and -6?

>>> positive = -9
>>> negative = -12
>>> while negative:
...    if positive:
...        print(negative)
...    positive += 3
...    negative += 3
______

I am still a beginner of it and thank you for answering my question.

I tried to use PythonTutor but I still not understand why.

cleochan
  • 1
  • 2
  • 1
    The while loop breaks when it’s condition is false. The only number that is "false" here is 0. – Pam Apr 08 '23 at 14:48
  • 1
    The `while` loop will continue while the variables are *truthy*. For numbers, only `0` is *falsey*, any other number is truthy. If the number in the condition never hits exactly `0`, it'll continue forever… – deceze Apr 08 '23 at 14:48
  • In the first example, `positive` is an integer. All integer values are considered to be "true", except for zero. `positive` is never equal to zero, because 28 is not a multiple of 3. – John Gordon Apr 08 '23 at 14:48

0 Answers0