Please Help me with this basic question

n = 10

i = 10

while i > 0:

 print i

 if i % 2 == 0:

       i = i/2


       i = i + 1

First, what is your best guess as to what this code is trying to do? Keep in mind, there are errors in this code, and there is no “right” answer as to its intent. Once you’ve decided what you feel is the goal of this code, share your thoughts on this while pointing out any errors. Show us your corrected version of this program.

On a mental cursory examination, the prints should be,


In other words, an infinite loop.

Agree with @mtf: an infinite loop, well-constructed. As such, can’t be improved.

(I suppose it could be an essay at coding the Collatz function, but is missing a factor of 3 in the assignment following “else”.)

1 Like

With i set to 2, the infinite loop begins at the point of convergence of the earlier function. This is a perfect loop to control a blink function. We could print a pipe, (|) and delay half a second, then print a backspace character, delay, then the pipe, etc. Would it were Python allowed it. (Mind, there is a blinking pipe on input.)

I tried this to see if it would render the backspace in the console…

>>> print (chr(124) + chr(8))
>>> input("|" + chr(8) )

Used to be able to emulate a blinking cursor in BASIC with a similar loop. Relies on the draw pencil staying on the line.

Funny enough, while the IDLE console won’t render the backspace character, Discourse does. Notice the,


Anyway, just a silliness segue, use of a toggle in an infinite loop.

>>> a = 1
>>> int(not a and 1)
>>> a = 0
>>> int(not a and 1)

JavaScript lets us do this…

 > ! 1 * 1
<- 0
 > ! 0 * 1
<- 1