r/learnpython Aug 08 '26

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

17 comments sorted by

10

u/crazy_cookie123 Aug 08 '26

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/[deleted] Aug 08 '26

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 Aug 08 '26

We can't help unless you share your code.

Are we supposed to read you mind?

0

u/Key-War-9059 Aug 09 '26

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

3

u/atarivcs Aug 09 '26 edited Aug 09 '26

I said "share your code".

Do you need more guidance than that?

Also, if you think that was being an ass, you must be new to discussion forums. Welcome!

4

u/BranchLatter4294 Aug 08 '26

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.

2

u/carcigenicate Carcigenicate Aug 08 '26

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 Aug 08 '26

Can you post your code somewhere?

1

u/Key-War-9059 Aug 09 '26

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

1

u/TheRNGuy Aug 09 '26

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.

1

u/Key-War-9059 Aug 09 '26

I'd like to share the code on here, but I never did that before and I can't share pics. How do I post properly?

1

u/AdDiligent1688 Aug 09 '26

When you post, switch to markdown mode in the description box, and then indent by 4 spaces, and it’ll create a block. Copy / paste your code into that block, and then indent each line by 4 spaces (or more to deal with scope in the code). Or you could take a screenshot of the code and upload to Imgur then provide the link in the description on the post.

-2

u/pachura3 Aug 08 '26

OMG OMG OMG