knerr cs21 notes...

back to schedule

WEEK03: booleans, logical operators, conditionals (if/else)
---------------------------------------------------------------
 W: review expressions, if/else, logical operators

EXPRESSIONS:

>>> x = 10
>>> y = 20
>>> x > y
False
>>> x < y
True
>>> x == y
False

  can also do this with letters

>>> ch = 'a'
>>> ch =='b'
False
>>> ch != 'b'
True
>>> ch > 'b'
False
>>> ch < 'b'
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
>>> 


  answer = raw_input("would you like to play a game? (y/n): ")

  if answer == 'y':
    print ">>> SUPER. let's play tic-tac-toe..."
  else:
    print "ok...quitting"


LOGICAL OPERATORS: and or not (in ??)

--> can combine conditions with "and" and "or"

>>> if speed < 70 and speed > 40:
...    print "no ticket...you can go"
... else:
...    print "you're either going too fast or two slow!"


--> can you impove the above play-a-game program to handle 
    more cases?

$ python playgame.py 
would you like to play a game? (y/n): yes
>>> SUPER. let's play tic-tac-toe...

$ python playgame.py 
would you like to play a game? (y/n): Yes
>>> SUPER. let's play tic-tac-toe...


--> can you write this program:

$ python lettercase.py 
phrase: Hello!
uppercase:  H
lowercase:  e
lowercase:  l
lowercase:  l
lowercase:  o
nonletter:  !

HINT:

  >>> ch = 'g'
  >>> ch > 'a' and ch < 'z'
  True
  >>> ch = 'G'
  >>> ch > 'a' and ch < 'z'
  False
  >>> 


--> can you write this program:

$ python isodd.py 
please enter an integer: 33
33 is O D D 

$ python isodd.py 
please enter an integer: 100
100 is EVEN