I keep getting an error message for this code even though everything I've looked at seems right. Anyone know what I'm doing wrong?
a function ends the moment a return keyword is reached, if a return keyword is reached in a loop, the loop simply breaks
I'm not really sure what that means
currently at line 5 your program reaches a return keyword in the first iteration of your loop, because return keywords cause function to end, the loop breaks
so your loop ends a bit prematurely given you have multiply every item in the list, not only the first one
I still don't understand
you do understand that you need to modify all elements in the list?
and i am telling, you only modify the first item (because of
I'm still not getting it though. I thought that the code on line 3 and 4 covered all of it?
yes, except you place the return inside your loop causing the loop to end prematurely
It gives me an error message if I place it outside of the loop though, so what am i doing wrong
can you copy paste an updated version of your code to the forum?
Seems fine to me?
Remicah, I recommend looking up "desk checking", and doing that with this code. In brief, "desk checking" means you go through your code step by step with pen and paper and write down what the code is doing. This is especially helpful for loops, which are a common source of error for new developers and seasoned developers alike (just look at the recent Cloudbleed issue).
To briefly (and incompletely) demonstrate desk checking on your original code that you screenshotted at the very top of this thread, you'd start with line 7,
print double_list(x), and write on your paper
print double_list(3, 5, 7) because that's what
x is. Then you'd walk through your
double_list function, replacing every variable with the actual value. So next you'd take line 3 and write on your paper
for 0 in range(0, 2).
3 becomes 3 * 2
return [6, 5, 7]
This is what stetim94 is trying to explain, that the
return keyword tells the program to stop everything, and return (or spit out) whatever comes next, which in your case would be
[6, 5, 7]. So the solution is to remove the indent on line 5, which you correctly did later in your second screenshot. Python isn't very clear on this, but indention is very important and actually means a lot in Python. if you write
for i in range(0, len(x)), eveything that is indented AND below that line becomes part of that
for loop. But if you remove the indention, it's no longer part of that
for loop. In your original code, that means that line 5,
return x, won't get evaluated until after the entire
for loop gets ran.
I hope this helps!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.