Simple For Loop


for i in range (1, 5):		#Start value, Exit value (loop won't run with this value as it exits, so needs to be desired final value + 1)
    print i:

Will output: 1 2 3 4

Reverse Loop


for i in range (5, -1, -1):		#Start value, Exit value (loop won't run with this value as it exits, so needs to be desired final value + 1), adjust value
    print i:

Will output: 5 4 3 2 1 0

Nested For Loops


for level in xrange(255, -1, -1):
    for index in xrange(0, 24):
        led_values[index] = level
    bus.write_i2c_block_data(PCA9626_ADDRESS, (0x80 | PCA9626_REG_PWM0), led_values)
    time.sleep(0.01)

For loop – Each item in a collection

for this_item in my_list:
    #Next item
    print(this_item)


#You can do a loop in 1 line if you wish:
for this_item in my_list: print(this_item)

For loop – Range

for index in range(6):    #Loop 6 times, from value 0 to 5
    #Next index
    print("Loop # " + str(index))

For loop by index

for index in range(0, len(my_array)):
    #Next index
    print("Loop # " + str(my_array[index]))

Loop Control

Exit loop
    break
Exit and start next iteration
    continue
Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *