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 675
悲哀的现实
悲哀的现实 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:54

    Well, for is a special statement that automatically defines the variable for you. It would be redundant to require you to declare the variable in advance.

    while is a general purpose loop construct. The condition for a while statement doesn't even have to include a variable; for example

    while True: 
    

    or

    while my_function() > 0:
    

提交回复
热议问题