Home > Software design >  Understand output of the while loop
Understand output of the while loop

Time:06-09

I have the following code:

def loop_mystery_exam1(i, j):
    while i != 0 and j != 0:
        i = i //j
        j = (j - 1) // 2
        print(str(i)   " "   str(j)   " ", end='')
    print(str(i))
    print(i   j)
    
loop_mystery_exam1(80, 9) 

I get this output:

8 4 2 1 2 0 2

2

Why there are only 2 outputs? I think there should be 3, since there are 3 print statements.

CodePudding user response:

Python's print method has the end with the default value of \n which means a new line, you can check it here.

That means you are overwriting this default behavior forcing your code to print i and j in the same line until print(str(i)) which will break the line.

If you are coding in an IDE, add a breakpoint in the while line and you will see it.

A suggestion here would be to remove the end='' of the first print, or write as the following:

def loop_mystery_exam1(i, j):
    while i != 0 and j != 0:
        i = i // j
        j = (j - 1) // 2
        print(f"i={i} ; j={j}")
    print(i)
    print(i   j)

CodePudding user response:

The first print statement runs three times. The first time it prints 8 4 , then 2 1 , then 2 0 . Each time, there is a trailing space, but no newline.

The second print statement prints 2 and then a newline.

The third print statement prints 0 and then a newline.

  • Related