Why do I not have to define the variable in a for loop using range(), but I do have to in a while loop in Python?

后端 未结 6 714
悲哀的现实
悲哀的现实 2021-01-18 17:36

I have the following code using a for loop:

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

Now the

6条回答
  •  没有蜡笔的小新
    2021-01-18 17:47

    Python for loops assign the variable and let you use it. We can transform a for loop into a while loop to understand how Python actually does it (hint: it uses iterables!):

    iterator = iter(iterable)  # fresh new iterator object
    done = False
    while not done:
        try:
            item = next(iterator)
        except StopIteration:
            done = True
        else:
            # inside code of a for loop, we can use `item` here
            pass
    

提交回复
热议问题