Home -> Control -> Conditionals


Definition: A conditional or condition is a statement that evaluates to True or False. (True and False are Boolean values.)

  • wikipage: if statements to determine whether a block of code should be evaluated.
  • wikipage: while loops to determine when to end the loop
  • wikipage: for loops to determine which values of the counter should be evaluated

EXAMPLES ON MY SAGE PAGE: Conditionals in Sage


Operator on objects Description
x == y Returns True if the two objects are equal and False if they are not equal.  Notice that == performs a comparison and not an assignment like = does.
x <> y Returns True if the objects are not equal and False if they are equal.
x != y Returns True if the objects are not equal and False if they are equal.
x < y Returns True if the left object is less than the right object and False if the left object is not less than the right object.
x <= y Returns True if the left object is less than or equal to the right object and False if the left object is not less than or equal to the right object.
x > y Returns True if the left object is greater than the right object and False if the left object is not greater than the right object.
x >= y Returns True if the left object is greater than or equal to the right object and False if the left object is not greater than or equal to the right object.
Operator on booleans Description
b1 and b2 Returns True if both booleans are true and False otherwise.
b1 or b2 Returns True if either or both booleans are true and False only if both are false.
not b1 Returns True if boolean is false and False if boolean is true.

  • if condition :
    • Works like a programming function, that is, you need a colon : and all command lines in block are indented. (See also page: if)
    • Example 1
      x=1
      if x<3 :
      print 'The value of x is less than 3.'
      x=x+2
      print 'We are now out of the first conditional block and x=', x
      if x<3 :
      print 'The value of x is less than 3.'
      x=x+2
      print 'We are now out of the second conditional block and now x=', x
      Result:
      The value of x is less than 3.
      We are now out of the first conditional block and x= 3
      We are now out of the first conditional block and x= 3 (see top 2 blocks of code of My Sage Page)

  • Other conditionals
    • Example 2 -see Example 1 on wikipage: while
    • Example 3 -see Example 5 on wikipage: for

Reference: Sage_for_Newbies, pp.28-33 (Ted Kosan)



Keywords: sage, conditional, condition, if, else, while, loops, for, control, repeating