Home > Blockchain >  Getting different output for different positioning of my print statement in python 3
Getting different output for different positioning of my print statement in python 3

Time:01-19

This is the normal code i was writing and this code has the desired output i wanted

a = [1,1,2,3,5,8,4,13,21,34,55,89]
less5num = []
for i in a:
    if i < 5:
        less5num.append(i)
        less5num.sort()
print(less5num)

Output
[1, 1, 2, 3, 4]

now, if i keep print inside the if loop i get a number pyramid

a = [1,1,2,3,5,8,4,13,21,34,55,89]
less5num = []
for i in a:
    if i<5:
        less5num.append(i)
        less5num.sort()
        print(less5num)

Output
[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 3]
[1, 1, 2, 3, 4]

if i keep print out of the if loop i get a recursive number pyramid

a = [1,1,2,3,5,8,4,13,21,34,55,89]
less5num = []
for i in a:
    if i<5:
        less5num.append(i)
        less5num.sort()
    print(less5num)

Output
[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3]
[1, 1, 2, 3, 4]
[1, 1, 2, 3, 4]
[1, 1, 2, 3, 4]
[1, 1, 2, 3, 4]
[1, 1, 2, 3, 4]
[1, 1, 2, 3, 4]

why is this hapenning?

CodePudding user response:

a = [1,1,2,3,5,8,4,13,21,34,55,89]
less5num = []
for i in a:
    if i<5:
        less5num.append(i)
        less5num.sort()
    # this print in loop but outside if statement
    print(less5num)

Your print is in loop but outside if statement. That's why all iterations are print in console

CodePudding user response:

In your first block of code, the print is not inside the for loop, it is executed after all the elements are iterated, only the numbers less than 5 are added to list and sorted.

In your second block of code, the print is inside the loop, and also only executes if number is less than 5, so only less number of times print is executed.

In your 3rd block of code, your print is in the for loop, but not within the if block, so when every element is encountered, a printing happens, so as many number of times as there are numbers in your list.

CodePudding user response:

If the print is outside the loop, it prints the list once with all numbers less than 5.

If it's inside the if you print the list once for every time you find a number less than 5. The list is mid creation so it grows larger.

If it's inside the loop, you print it once for every number in the loop.

You can visualize it using pythontutor.

CodePudding user response:

First if

There is 5 elements in list less than 5 so you print it 5 times.

[1,1,2,3,4]

Second if

Loop ends after all value in list. There is 12 elements in list so you print it 12 times.

[1,1,2,3,5,8,4,13,21,34,55,89]
  •  Tags:  
  • Related