Main.Conditionals History

Hide minor edits - Show changes to markup

January 28, 2010, at 03:02 PM MST by 129.82.44.241 -
Added lines 1-58:

(:source lang=python:)

"""Conditionals: the if statement"""

  1. the 'if' statement

x = 1 if x > 0 :

    print "x is positive"
  1. the 'if - else' statement - what to do if the condition
  2. does not hold

if x % 2 == 0:

    print x, "is even"

else:

    print x, "is odd"
  1. note: the modulus operator yields the remainder when
  2. the first operand is divided by the second
  3. when there are more than two possibilities use 'elif'

x = 1 y = 1 if x < y:

    print x, "is less than", y

elif x > y:

    print x, "is greater than", y

else:

    print x, "and", y, "are equal"
  1. nested conditionals
  2. One conditional can also be nested within another.

if x == y:

    print x, "and", y, "are equal"

else:

    if x < y:
        print x, "is less than", y
    else:
        print x, "is greater than", y
  1. we can compare strings using == and our other operators:

name1 = "Mark" name2 = "Mary" if name1 == name2 :

    print "the names are the same"

else :

    print "the names are NOT the same"

if name1 > name2 :

    print name1, "is greater than", name2

else :

    print name1, "is not greater than", name2

(:sourceend:)