Week 2, Wednesday: accumulator, print formatting

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:

You 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]

Your Turn!

Try 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

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:

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: