Computer Science 15-110, Spring 2011
Class Notes: Conditionals
Conditionals
if (today == "monday"):
if (hour < 12):
print "Alice"
else:
print "Bob"
else:
if (hour < 10)
print "Chad"
else:
print "Donna"
Wrong | Right |
if (b) return True else: return False |
return b |
Wrong | Right |
if (not
b): print "no" else: print "yes" Or: if (b == False): print "no" else: print "yes" |
if (b): print "yes" else: print "no" Or: if (b == True): print "yes" else: print "no" |
Wrong | Right |
if
(b1): if (b2): print "both!" |
if (b1 and b2): print "both!" |
Wrong | Right |
if (b): print "yes" if (not b): print "no" |
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!" |
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem