Main.Conditionals History
Hide minor edits - Show changes to markup
January 28, 2010, at 03:02 PM MST
by -
Added lines 1-58:
(:source lang=python:)
"""Conditionals: the if statement"""
- the 'if' statement
x = 1 if x > 0 :
print "x is positive"
- the 'if - else' statement - what to do if the condition
- does not hold
if x % 2 == 0:
print x, "is even"
else:
print x, "is odd"
- note: the modulus operator yields the remainder when
- the first operand is divided by the second
- 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"
- nested conditionals
- 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
- 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:)
