knerr cs21 notes...

back to schedule

WEEK03: booleans, logical operators, conditionals (if/else)
---------------------------------------------------------------
 M: review quiz 1, booleans, if/else

LAB2: due Tuesday

FROM QUIZ 1...this is *not* and accumulator (result is always 5):

 def main():               
    result = 5           
    for i in range(10):
        print result * i    

    print "result = %d" % (result)
    print "     i = %d" % (i)

 main()


 this one *is* an accumulator. what would it print??

 def main():               
    result = 5           
    for i in range(4):
        result = result + i
        print result 

    print "result = %d" % (result)
    print "     i = %d" % (i)

 main()

 can also accumulate strings, like this:

def main():
  title = raw_input("your title: ")
  newtitle = "\n\n   "
  for ch in title:
    newtitle = newtitle + ch + "  "

  newtitle = newtitle + "\n\n "
  print newtitle

main()


BOOLEANS...a new type

>>> x = True
>>> type(x)
<type 'bool'>
>>> y = true
Traceback (most recent call last):
  File < stdin > line 1, in < module >
NameError: name 'true' is not defined
>>> z = False
>>> type(z)
<type 'bool'>
>>> print z
False
>>> 


COMPARISON OPERATORS (be careful with ==)

>>> i=10
>>> j=15
>>> i < j
True
>>> i > j
False
>>> i == j
False
>>> i >= j
False
>>> i != j
True
>>> 


CONDITIONAL STATEMENTS:

if < condition >
  do this
  and this
else:
  do that

--> can do if without an else


>>> if i < j:
...   print "i is less than j"
... 
i is less than j


>>> if i == j:
...   print "i and j are equal"
... else:
...   print "i is not equal to j"
... 
i is not equal to j
>>>