Python for loop?

前端 未结 6 1521
醉酒成梦
醉酒成梦 2021-01-24 10:04

I am having trouble understanding a Python for loop. For example, here is some code I\'ve made while I\'m learning:

board = []
for i in range (0,5):
    board.ap         


        
6条回答
  •  执笔经年
    2021-01-24 10:34

    The for loop iterates over the given list of objects which is [0, 1, 2, 3, 4] obtained from range(0,5) and in every iteration, you need a variable to get the iterated value. That is the use i here. You can replace it with any variable to get the value.

    for n in range(0, 5):
        print n    #prints 0, then 1,  then 2, then 3,then 4 in each iteration
    

    Another example:

    for n in ('a', 'b', 'c'):
        print n    #prints a, then b,  then c in each iteration
    

    But in the code you have given, the variable i is not used. It is being used. just to iterate over the list of objects.

提交回复
热议问题