Here is the average.py
program from last time:
"""
simple for-loop accumulator program
J. Knerr
Spring 2013
"""
def main():
ngrades = int(raw_input("\nNumber of grades: "))
total = 0
for n in range(ngrades):
grade = float(raw_input("grade: "))
total = total + grade
avegr = total/float(ngrades)
print "Average grade = %.1f\n" % (avegr)
main()
Notes:
total/ngrades
be?\n
is called a newline character%f
stuff is what we will learn today: print formattingfor
loopYou can accumulate numbers, like above, as well as lists and strings:
>>> S = ""
>>> for i in range(10):
... S += "X"
...
>>> print(S)
XXXXXXXXXX
>>> L = []
>>> for i in range(10):
... L = L + [i]
... print(L)
...
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+=
is just shorthand notation for S = S + whatever
L + [i]
) works, but is klunky. We will see
a better way to do that in a few weeksTry writing this one, where the user enters a string and a character:
$ python addchar.py
enter a string: hello
enter a char: *
*h*e*l*l*o*
Print formatting allow you to easily control the output format of all types of variables: strings, integers, and floats. For example, suppose I had three variables:
>>> name = "Mike Trout"
>>> hrs = 41
>>> avg = .299
and wanted to print something like this:
Mike Trout batted 0.299 and hit 41home runs this year
We could do it like this:
>>> print(name+" batted "+str(avg)+" and hit "+str(hrs)+ "home runs this year")
or we could use print formatting:
>>> print("%s batted %.3f and hit %d home runs this year" % (name,avg,hrs))
Mike Trout batted 0.299 and hit 41 home runs this year
Notes:
name,avg,hrs
) gets substituted in the the string
for the corresponding place-holder (%s
, %.3f
, %d
)You can also add width and precision specifiers to the format specifiers.
For example, printing a string with %20s
means pad the left of the string with spaces,
if needed, so the whole thing is 20 characters wide. Same for %20d
. For a float,
you can specify both the width and the precision: %8.2f
means a width of 8, with
only two digits after the decimal point.
Here is one last example, using what are called parallel lists:
def main():
# parallel lists
players = ["Vladimir Radmanovic","Lou Williams","Lebron James", "Kevin Durant", \
"Kobe Bryant","Kevin Garnett"]
ppg = [0, 11.5, 30.3, 28.5, 30.0, 19.2] # points-per-game
games = [2, 13, 23, 20, 12, 20] # games played
for i in range(len(players)):
print("%d: %20s %4.1f %2d" % (i, players[i], ppg[i], games[i]))
And here is how the output looks:
0: Vladimir Radmanovic 0.0 2
1: Lou Williams 11.5 13
2: Lebron James 30.3 23
3: Kevin Durant 28.5 20
4: Kobe Bryant 30.0 12
5: Kevin Garnett 19.2 20
Notes:
len()
, yet, but I bet you can guess what it returns!len(players)
is 6, then what is range(6)
?range(len(list))
pattern is seen a lot in python!for
loop is technically only over the players list, but I can use the i
variable on any list (hence they are called parallel lists) -- we'll see a
better way to structure data like this in the second half of the course%20s
, see how all the names line up!%4.1f
-- the width of 4 includes the decimal point%2d
for the games played