Home > Control -> Loops -> while Loops


Basic syntax: while condition :  where condition is a boolean, that is, it evaluates to either true or false.

  • The while loop is ONLY for repeating a set of commands (see also: loops and for loops)

     Remember: some command in your loop must eventually make the condition false or you will be in there forever (see below +).

EXAMPLES ON MY SAGE PAGE: Loops in Sage



  • while loops
    • Works like a programming function, that is, you need a colon : and all command lines in loop are indented.
    • Example 1
      x=1; y=3
      while x<3 :
      x=x+1
      print x, y, 'looping'
      print 'This line is not indented so NOT in the loop and will only print once.'
      Result:
      2 3  looping
      3 3  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 one more loop than Example 1 since condition: x<=3
      x=1; y=3
      while x<=3 :
      x=x+1
      print x, y, 'looping'
      print 'This line is not indented so NOT in the loop and will only print once.'
      Result:
      2 3  looping
      3 3  looping
      4 3  looping
      This line is not indented so NOT in the loop and will only print once.   (see bottom of My Sage Page)

Long-Running Loops, Infinite Loops, And Interrupting Execution - Ted Kosan

3.13 Long-Running Loops, Infinite Loops, And Interrupting Execution
It is easy to create a loop that will execute a large number of times, or even an infinite number of times, either on purpose or by mistake. When you execute a program that contains an infinite loop, it will run until you tell SAGE to interrupt its execution.This is done by selecting the Action menu which is near the upper left part of the worksheet and then selecting the Interrupt menu item. Programs with long-running loops can be interrupted this way too. In both cases, the vertical green execution bar will indicate that the program is currently executing and the green bar will disappear after the program has been interrupted.

This program contains an infinite loop:

#Infinite loop example program.
x = 1
while x < 10 :
answer = x + 1

Since the contents of x is never changed inside the loop, the expression x < 10 always evaluates to True which causes the loop to continue looping. Execute this program now and then interrupt it using the worksheet's Interrupt command. Sometimes simply interrupting the worksheet is not enough to stop execution and then you will need to select Action -> Restart worksheet. When a worksheet is restarted, however, all variables are set back to their initial conditions so the cells that assigned values to these variables will each need to be executed again.

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


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