Python Forum
question about for loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: question about for loop (/thread-27472.html)



question about for loop - Than999 - Jun-08-2020

How come in the output of this code there is an extra 4? Shouldn't it only display a single 4 value as the last value in this output?

num = 10
for num in range(5):
    print(num)
print(num)



RE: question about for loop - pyzyx3qwerty - Jun-08-2020

In the first print statement, you call all the numbers till 5 excluding 5, so it will print 1,2,3,4. Now the last number in that thing becomes num and therefore, an extra 4 is printed because of your print statement outside the loop


RE: question about for loop - Larz60+ - Jun-08-2020

Note also, that the statement num = 10 is overwritten in step 2.


RE: question about for loop - Emekadavid - Jun-08-2020

This is just what I love about Python. It allows you to reuse a variable several times and reference different values. But that flexibility comes with a caveat. If not careful you might introduce errors into your code and end up wondering why you got a semantic error.


RE: question about for loop - deanhystad - Jun-08-2020

I'm confused about what you don't understand; what print does or how loops work.
for num in range(5):
    print(num)
This is a loop. Loops are used when you want to execute the same code multiple times. This part controls how often the loop executes and also provides a value for num:
for num in range(5)
This is the code that is executed multiple times:
    print(num)
The loop is essentially doing this:
print(0)
print(1)
print(2)
print(3)
print(4)
print is a function that evaluates the statement inside the parenthesis and prints it to standard output (or a different destination if specified.


RE: question about for loop - Emekadavid - Jun-09-2020

As you can go forwards, you can also go backwards. That makes your programming flexible and convenient. Here is a code that moves through the above number line backwards. Just make the stop a negative value.
for i in range(4, -1, -1) :
    print(i)
what it prints out is:
4
3
2
1
0