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?
问题 I have the following code using a for loop: total = 0 for num in range(101): total = total + num print(total) Now the same result using a while loop: num = 0 total = 0 while num <= 99: num = num + 1 total = total + num print(total) Why is it that I do not have to define num in the first case, but I do have to define it in the second? Are they both not variables? 回答1: I'd like to approach this question from a slightly different perspective. If we look at the official Python grammar