I have the following code using a for loop:
total = 0
for num in range(101):
total = total + num
print(total)
Now the
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