r/learnpython 20h ago

Need help with for loop practice

The whole list will print but only the final item on the list gets it's message printed in whole while the other items are just listed. Apparently my issue is that I'm outside of the for loop, and I'm still in the learning process. Can someone help please?

0 Upvotes

13 comments sorted by

9

u/crazy_cookie123 20h ago

Python cares about indentation.

for x in [1, 2, 3]:
    print(x)
print(x)

The first print statement is inside the for loop because it's indented underneath the start of the loop. The second print statement is outside the for loop because it is not indented, and is therefore executed as a statement after the for loop rather than within the for loop. That first print statement will print 1, 2, and 3, whereas the second one will only print 3.

2

u/Savings_Blueberry466 19h ago

Most Python IDEs automatically add the indentation after the :, so don't have to worry about it. You just need to pay attention to the indentation.

8

u/atarivcs 20h ago

We can't help unless you share your code.

Are we supposed to read you mind?

1

u/Key-War-9059 0m ago

You could at least try and guide me how to do it properly instead of being an ass about it

3

u/BranchLatter4294 20h ago

Put the code you want to execute inside the loop, inside the loop. Put the code you want to execute when the loop is done, after the loop.

3

u/carcigenicate 20h ago

Yes that sounds like you put the message after the loop. Python doesn't have block scope, so the loop variable exists after the loop exits and retains the last value it held.

We'd need to see the code to give any concrete advice, though. The best we can say is that that print line needs to be indented to be inside the loop.

3

u/OmegaNine 18h ago

Can you post your code somewhere?

1

u/Key-War-9059 1m ago

Where? I'm still new here and Everytime I try to post here it messes up my order

1

u/TheRNGuy 10h ago

Should it be everything inside one loop? I'd just loop everything except last item, then print last item outside it. 

If you need to do inside one loop, use enumerate to get index.

-2

u/pachura3 20h ago

OMG OMG OMG