What is wrong with my code?
Removing from the same list as you are looping over, is a recipe for disaster
the moment you remove an item from the list, the empty spot has to be filled:
4 6 8 #items in list 0 1 2 #indexes
lets say you remove
4 from index 0, then we get an empty slot, which can’t be, so the slot is filled in the following way:
6 8 0 1
but the loop then does move on to the next index (from 0 to 1), skipping the item (6) that is now at index 0.
Mod is correct.
However I believe there is a bit more here. From looking at your past work and seeing this, I have found that, fundamentally, your understanding of programming logic needs a bit of review.
Your for loop is spot on. So, we will move on to the while loop.
What is the while loop telling us?
While our number is not divisible by two we are going to keep running this code below
In other words:
As long as we have an odd number, we are going to run the code below
Okay that is fine. So, what is the result. The next piece of code is a conditional. What is this telling us?
If the number is even, remove the number from the list
Okay. So what happens after that…well, nothing. We just repeat the list.
We encounter problem #1: Infinite while loop.
Think about it, our variable “num” will always be odd. Therefore, the while loop will run indefinitely. In our while loops, we need a condition that will make this “False” at some point. Before we write any code, we need to consider another thing. What if the number we are at in our list is even?
We have problem #2: Unreachable Condition
Our while loop will only run if the “num” variable is odd. So, if our “num” variable is even, will we be able to reach the condition to remove the number? No, because we can only get the the condition if we have an odd number. This presents an interesting problem.
So, how do we solve this. Well, I could tell you the answer. However, this is a great opportunity for you to understand how your brain works and how to communicate to the computer.
First, take out a piece of paper and something to right with.
Second, go through the code you wrote. Write it out in a simple way.
Third, Follow your own instructions and see if you would be able to do the task based on your current instructions.
This going to be a recurring problem in your code if we don’t nip it in the bud now. Take the time, and see if you can find the logic errors. Happy Coding