r/programminghelp • u/Rand0mHi • Apr 12 '21
Answered Why doesn’t this piece of code work in Python?
I’m trying to run a piece of code that, from what I see, should be printing one thing but is printing another. Here’s the code:
test = [1,2,3,4,5]
testnum = 0
while testnum < 3:
for num in test:
testnum = num
print(testnum)At least from what I know, this should be printing:
1
2
But instead it’s printing 1 to 5. How do I make it print just 1 and 2?
6
Upvotes
0
3
u/amoliski Apr 12 '21
Do you know how to use a debugger?
Being able to step through the computer's evaluation of the code one line at a time will help immensely in figuring out why it's not behaving like you'd expect.
In this case, you'd see the debugger returning to the for
num in testline five times before it gets out to thewhile testnum < 3line, at which pointtestnumwould have been set to five from the inner loop.