WEEK03: booleans, logical operators, conditionals (if/else)
---------------------------------------------------------------
M: review quiz 1, hand back lab 1, booleans, if/else
LAB2: due Tuesday
REVIEW OF INDEXING FROM LAST WEEK + PRINT FORMATTING
- print formatting is a better way to format your print statements
- use these tags in your strings as placeholders for variables:
%d for ints
%f for floats
%s for strings
- for example:
>>> name = "Ryan Howard"
>>> hrs = 10
>>> ave = 0.290
>>>
>>> print "%s has hit %d home runs and is batting %f" % (name,hrs,ave)
Ryan Howard has hit 10 home runs and is batting 0.290000
- use %20s to force a 20-character field width:
>>> print "%20s has hit %d home runs and is batting %f" % (name,hrs,ave)
Ryan Howard has hit 10 home runs and is batting 0.290000
- use %.3f to force only 3 digits after the decimal:
>>> print "%s has hit %d home runs and is batting %.3f" % (name,hrs,ave)
Ryan Howard has hit 10 home runs and is batting 0.290
WRITE THIS PROGRAM:
- given 3 parallel lists:
players = ["Lebron James", "Kevin Durant", "Kobe Bryant", "Kevin Garnett"]
ppg = [30.3, 28.5, 30.0, 19.2] # points-per-game
games = [23, 20, 12, 20] # games played
- write a program to print out the data formatted like this:
2012 NBA Playoff Stats:
-----------------------
Lebron James averaged 30.3 points/game in 23 games
Kevin Durant averaged 28.5 points/game in 20 games
Kobe Bryant averaged 30.0 points/game in 12 games
Kevin Garnett averaged 19.2 points/game in 20 games
- how can we use a for loop to work through all 3 lists?
for i in range(len(players)):
print "%15s averaged %.1f points/game in %d games" % (players[i], ppg[i], games[i])
what is i in the above code?
BRANCHING...how do we do this in a program???
$ python speed.py
How fast were you going? 50
OK...off you go.
$ python speed.py
How fast were you going? 75
that's too fast....here's your ticket
SLOW DOWN!!!!!!!!!!!!!
** need some way to test something and decide if it's True
or False. And if it's True, do one thing; if it's False,
do something else. This is called a BRANCH, as execution
of your program can follow one of two (or more) paths
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
--> condition is an expression that evaluates to True or False
--> 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
>>>
FOR LOOP WORKSHEET: /home/jk/inclass/forloopsWorksheet.py