For loops

Courses

For loops
To repeat code, the for keyword can be used. To execute a line of code 10 times we can do:

for i in range(1,11):
    print(i)

The last number (11) is not included. This will output the numbers 1 to 10. Python itself starts counting from 0, so this code will also work:

for i in range(0,10):
    print(i)

but will output 0 to 9.

Illustrated in this graphic:
for-loop

The code is repeated while the condition is True. In this case the condition is: i < 10. Every iteration (round), the variable i is updated. Nested loops
Loops can be combined:

for i in range(0,10):
    for j in range(0,10):
        print(i,' ',j)

In this case we have a multidimensional loops. It will iterate over the entire coordinate range (0,0) to (9,9)

Variables
While loop

10 thoughts on “For loops

  1. Reply
    anonymous - March 27, 2016

    Seems easier to use than Java!!

  2. Reply
    Mithil - April 5, 2016

    when i pres enter after the first line it just gives me three dots?

    1. Reply
      admin - May 18, 2016

      Create a text file with the code and name it ‘loop.py’. Then execute using ‘python loop.py’. Alternatively install PyCharm. https://www.jetbrains.com/pycharm/

  3. Reply
    anonymous - April 7, 2016

    Nothing at the end, just stop indenting?

    1. Reply
      admin - April 12, 2016

      Yes, code blocks are created using indenting. To continue the program just go back to the normal indention.

  4. Reply
    nimda - April 29, 2016

    // Reverse loop
    for i in range(10,-2,-2):
    print (i,end=” ^^ “)

    1. Reply
      Bridgeman - June 25, 2016

      Just use ‘ ^^ ‘ single quotes, runs better…

  5. Reply
    Diego - May 27, 2016

    You have to add () to the print sentence to run
    for i in range(0,10):
    for j in range(0,10):
    print (i,’ ‘,j)

  6. Reply
    Ray - June 4, 2016

    on the nested loops section, line 3 should be print(i, ‘ ‘, j)
    I’m using python 3

    1. Reply
      admin - June 5, 2016

      Thanks, updated the line

Leave a Reply

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