bagustris 2 years ago Exercise 1.15 - Buggy loop. Anyone can explain the bugs in the code and give solution example?

• This Question is Open
1. e.mccormick

n=10 i=10 while i>0: print i if i % 2 ==0: i=i/2 else: i=i+1 That one? Well, look at the condition for stopping. \(i\le0\) would drop out of the loop. Why might that not happen? Here is a clue: What if I changed it to i=10.0? Why is that different? What does it do to the math? The diffeence is partially related to the answer.

2. bagustris

Yes, that assignment. If change i=10 to i=10.0, it is resulting unlimited looping, the different just the shown result, it changes from 1,2,1,2... to 1.0,2.0,1.0,2.0....

3. e.mccormick

That is true... but I wanted to point out what the modulus part does. You never see anything in wither integer or floating point mode that approaches an i of 0, right?

4. e.mccormick

You ask for a solution example... and there simply is not one. This is not intended to be part of working code. It is just there to show how you can make an infinite loop if you are not careful. The "solution" is that when you write a full program or useful piece of code, you test to make sure the loops exit!

5. bagustris

OK. I got, it. First, I change the last line to i = i - 1, to make loop works. Then, I assume this code is designed to print 10, 9, 8,...1 in loop.

6. e.mccormick

Well, it would not be intended to count down because it uses division. But if you wanted code to do half steps to count down by halfs, and then add one if you did not have an even number, it could do that if you do your change of i=i-1.

7. sune

I'm also busy with the Buggy loop at the moment. I think the easiest is to change while i>0 to while i>1. Then the code will do exactly the same thing, it will just stop at 1.

8. e.mccormick

@sune Another issue to think about is why is n there? They put n=10 in the code for a reason. What was it?

9. sune

@e.mccormick That is a very good question. I just ignored n in my first try. I've relooked at it and changed the else statement to: i=n+1. Then when i becomes 5, it stays 5 and n decreases with 1 each time.

10. e.mccormick

I think that the purpose of the buggy code problem is to show you that there are lots of things it could have intended, and that there is no way to pick the right thing because the code is very vague. A couple comments in there anywhere and the intent would have been much clearer.

11. AppylPye

Yeah, as @e.mccormick notes, the intent of the programmer is difficult to judge when there are bugs and the comments are inadequate. So, while it may be difficult to "State what you think Ben was trying to do ...", if you've come up with a number of possibilities, and fixes for the bugs based on each of those possibilities, you've learned some useful stuff. Poor Ben ;(