r/programminghelp • • 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

2 comments sorted by

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 test line five times before it gets out to the while testnum < 3 line, at which point testnum would have been set to five from the inner loop.

0

u/[deleted] Apr 12 '21

[deleted]

4

u/Rand0mHi Apr 12 '21

You’re right, thank you!