Python for loop?

前端 未结 6 1522
醉酒成梦
醉酒成梦 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:25

    In short, i refers to the current element in the list.

    Your list is defined as: 0, 1, 2, 3, 4 and 5. Therefore i will iterate this list and assign itself to the next item, i is 0, next iteration i will be 1, next iteration i will be 2 etc.

    Directly from python.org:

    The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended)

    words = ['cat', 'window', 'defenestrate']
    for w in words:
     print w, len(w)
    

    Results in:

    • cat 3
    • window 6
    • defenestrate 12

    http://docs.python.org/2/tutorial/controlflow.html

提交回复
热议问题