Home > Control -> Loops -> for Loops


Basic syntax: for j in range(n)   or   for j in [s..t]   where j is a variable name, n is a positive integer and s and t are numbers s≤t.

     The variable j is the "counter". See Counters. Each time through a for loop, the counter is automatically incremented.
     Remember: range(n) counts from 0 to n-1 (inclusive) and [s..t] counts starting from s and increasing by 1 until it is >t .
     Options for step size and conditional if are given in examples below.

EXAMPLES ON MY SAGE PAGE: Loops in Sage


Looping is the principle of repeated cycling. There are two main uses of loops. (see also: loops and while loops)

  • A loop for repeating a set of commands
  • A loop inside a command - usually for creating or processsing a list

  • for loops for repeating a set of commands
    • Works like a programming function, that is, you need a colon : and all command lines in loop are indented.
    • Example 1
      x=-3
      for j in range(4) :
      x=x+1
      print j, x, 'looping'
      print 'This line is not indented so NOT in the loop and will only print once.'
      Result:
      0  -2  looping
      1  -1  looping
      2  0  looping
      3  1  looping
      This line is not indented so NOT in the loop and will only print once.   (see bottom of My Sage Page)

    • Example 2 - gives exactly same result as Example 1, pop is just a different variable name
      x=-3
      for pop in [0..3] :
      x=x+1
      print pop, x, 'looping'
      print 'This line is not indented so NOT in the loop and will only print once.'

  • for loops inside a command - usually for creating or processing a list
    • Example 3
      # The brackets create a list in sage. Notice no colon or indentation.
      a=[ j for j in range(4) ]
      print a
      Result:
      [0, 1, 2, 3]   (see bottom of My Sage Page)

    • Example 4
      # Here we have added a step size in the [ .. ] counter so the count is -2,0,2 instead of -2,-1,0,1,2,3
      a=[ 2*j for j in [-2..3,step=2] ]
      print a
      Result:
      [-4, 0, 4]

    • Example 5
      # Here we have added a condition that j be even so again the count is -2,0,2 instead of -2,-1,0,1,2,3. Notice the double equals == to test for equality.
      a=[ 2*j for j in [-2..3] if int(j/2)==j/2 ]
      print a
      Result:
      [-4, 0, 4]

    • Example 6
      # The sum() command "sums" the elements of the list so that the command show() will put them all in one plot; the brackets create a list in sage, the point() command creates points with the option added that their size be 20.
      a=sum([ point( (j,2*j), size=20) for j in [-2..2] ] )
      show(a, figsize=4, aspect_ratio=1)
      Result:

Reference: Sage_for_Newbies, pp.35-37 (Ted Kosan)


blank15.pngblank15.pngblank15.pngblank15.pngfor_plot.png

Keywords: sage, for, loops, while, control, repeating, conditional, lists