-1

In this Python argument:

total = 0
for num in range(101):
    total = total + num
print(total)

After I run the code in the Python IDLE shell (it runs correctly, returning a value of 5050) if I ask it to return the value of num, it returns 100.

Why? I never assigned num a value? Is the for loop assigning it a value?

jonrsharpe
  • 99,167
  • 19
  • 183
  • 334
py.noob
  • 3
  • 1
  • This question has already been asked here https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops – Sri Apr 13 '20 at 17:00
  • You did assign `num` a value using the `for` loop. `num` will take on the values `0`, `1`, ... `100` each iteration. At the end of the loop `num` will contain the value from the last iteration. – Cory Kramer Apr 13 '20 at 17:00
  • Yes, the for loop is assigning it a value. – jonrsharpe Apr 13 '20 at 17:00
  • `num` is assigned a value each time through the `for` loop. Upon exit from the loop, it retains the last value, which is `100`. – Tom Karzes Apr 13 '20 at 17:00
  • 2
    Does this answer your question? [Scoping in Python 'for' loops](https://stackoverflow.com/questions/3611760/scoping-in-python-for-loops) – Tom Karzes Apr 13 '20 at 17:02

3 Answers3

0

The for loop in python does not create a scope. That means that variables defined in the for loop, also still exist after the for loop. This is different to how this works in many other languages, though quite useful at times.

Your for loop defines the variable num. It iterates over the value from 0 to 100 (including the 100). Every iteration it puts an integer into the variable num that's one higher than in the previous iteration, stopping at 100.

At this point num is still defined, and returning it indeed gives 100.

jonathan
  • 455
  • 3
  • 12
0

The variable num gets assigned a value in the for loop. The range specified is from 0-100, so at the end of the loop the value of num will be 100.

Oliver Mason
  • 1,451
  • 1
  • 11
  • 23
0

range is a generator.

For each loop iteration num is incremented starting at 0.

When you say range(101) it actually takes all values in [0,101)

So, in your example, it does not take the value 101.

range() is defined like

range(start, stop, step)

start and step are not mandatory

zxcyq
  • 1
  • 2