简体   繁体   中英

Why does num = 100?

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?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM