Guided Project: Exploring Hacker News Posts if / elif question

Hello! I’ve sorted out my issue, but I’m not sure why my solution worked, hoping someone could answer a fundamental question I have about formatting an if else block like if/if/else vs. if/elif/else in my two images below.

For a reason I don’t know, if I format the blocks as if/if/else as seen in the image below, the “Ask HN” posts end up in BOTH the ask_posts and other_posts lists. Why is the else block still executing after the first if block is fulfilled? And why is it only doing it for only the first if block, and not the second if block?

I see that if i just format it like if/elif/else, it works. I have read if you are going for mutually exclusive results from your if/else block, you should use elif for each block in between the if and else, I’m just not exactly sure why this works this way.

Any answers appreciated! Hope you all have a wonderful weekend.

Hi @djd7930 ,

When you have if - elif - else statement, it works together as one block. If any of the condition satisfies, it skip other parts and move to the next block of code. For example, if if condition is True, it executes whatever it is supposed to execute ( in this case appending to a list) and jumps out of the if-elif-else block. So in short whichever clause (if/elif/else) becomes True FIRST gets executed and then it jumps out of the block.

When you do If - if- else, it becomes two blocks. One if block and the second if-else block. And when it sequentially executes the lines of code, it first executes if block (if it is true, appends the list, if it is false jumps to the next if-else block) and then goes to the next ‘if-else’ block.

So here the if gets executed twice because they are two different blocks of codes unlike if-elif-else block which is one block of code.

Does it make sense?

So with how Python digests if/else blocks… the if / if / else I was essentially making - an if block, and a second if/else block, rather than if / elif / else which would form a single block. That would make sense that it was getting added to both lists.

Perfectly clear! Thank you very much for the explanation.

1 Like

Glad it sorted out your doubt @djd7930 . If you have no further questions please mark this thread as solved. Thank you.