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)

 

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

  1. TW79

    9 months ago

    How does the “While” command work? How can I set a particular number of times for a loop to run then exit?

  2. Anonymous

    6 months ago

    Here is an example I use on some LED’s
    set a counter, initiate the while, increment the counter in the loop.
    It is the indenting that defines the while loop.
    I am new at this so excuse the inelegance.

    i=0
    while i< 200:

    IO.output(6,1)

    time.sleep(1)

    IO.output(5,False)

    time.sleep(1)
    i=i+1
    if IO.input(21) ==0:
    emerg_pgm_term()
    break

    print(" Loop completed is",i)
    IO.output(4,False)
    IO.output(5,False)
    IO.output(6,False)
    IO.output(5,0)
    IO.output(20,0)
    IO.output(19,0)
    IO.output(20,0)

    print('loop completes normally. Program terminates')

Comments

Your email address will not be published.