Computer Science 15-112, Spring 2012
Class Notes: Conditionals
Conditionals
if (2 < 1):
if (3 == 3):
print "a"
else:
print "b"
else:
if (4 == 4):
print "c"
else:
print "d"
print "first:"
if (2 < 1):
if (3 == 3):
print "a"
else:
print "b"
print "second:"
if (2 < 1):
if (3 == 3):
print "c"
else:
print "d"
age = 42Same logic, after applying DeMorgan's Law:
if ((age >= 6) and (age <= 21)):
print "student"
elif (not ((age < 6) or (age > 75))):
print "professional"
age = 42 if ((age >= 6) and (age <= 21)): print "student" elif ((age >= 6) and (age <= 75)): print "professional"Same logic again, sharing a common condition:
age = 42 if (age >= 6): if (age <= 21): print "student" elif (age <= 75): print "professional"
And why we parenthesize...:
print not True and False print not (True and False)
if (2 < 1):
pass
else:
print "sometimes you may need pass, but this is not one of them!"
x = 3 if (1 < 2) else 4A Somewhat Better Example:
print x
x = 5 if (1 > 2) else 6
print x
p = 5
print "I saw",p,"people" if (p>1) else "person"
p = 1
print "I saw",p,"people" if (p>1) else "person"
Wrong | Right |
b = True if (not b): print "no" else: print "yes" Or: b = True if (b == False): print "no" else: print "yes" |
b = True if (b): print "yes" else: print "no" Or: b = True if (b == True): print "yes" else: print "no" |
Wrong | Right |
b = False if (b): pass else: print "no" |
b = False if (not b): print "no" Or: b = False if (b == False): print "no" |
Wrong | Right |
b1 = True b2 = True if (b1): if (b2): print "both!" |
b1 = True b2 = True if (b1 and b2): print "both!" |
Wrong | Right |
b = True if (b): print "yes" if (not b): print "no" |
b = True if (b): print "yes" else: print "no" |
Another Example:
Wrong | Right |
x = 10 if (x < 5): print "small" if ((x >= 5) and (x < 10)): print "medium" if ((x >= 10) and (x < 15)): print "large" if (x >= 15): print "extra large" |
x = 10 if (x < 5): print "small" elif (x < 10): print "medium" elif (x < 15): print "large" else: print "extra large" |
Yet Another Example:
Wrong | Right |
c = 'a' if ((c >= 'A') and (c <= 'Z')): print "Uppercase!" if ((c >= 'a') and (c <= 'z')): print "lowercase!" if ((c < 'A') or \ ((c > 'Z') and (c < 'a')) or \ (c > 'z')): print "not a letter!" |
c = 'a' if ((c >= 'A') and (c <= 'Z')): print "Uppercase!" elif ((c >= 'a') and (c <= 'z')): print "lowercase!" else: print "not a letter!" |
Wrong | Right |
x = 42 y = ((x > 0) and 99) |
x = 42 if (x > 0): y = 99 |
Another example:
Wrong | Right |
x = 42 y = (((x > 0) and 99) or ((x < 0) and 88) or 77) |
x = 42 if (x > 0): y = 99 elif (x < 0): y = 88 else: y = 77 |
Wrong | Right |
x = 42 y = ((x > 0) * 99) |
x = 42 if (x > 0): y = 99 else: y = 0 # or, if you prefer... y = 99 if (x > 0) else 0 |
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem