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/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*

One way to do this is with a string accumulator. Start with an empty string:

newstr = ""

Then go through the given string, one character at a time, adding both the character from the string (ch) as well as the new character (char):

string = raw_input("enter a string: ")
char   = raw_input("  enter a char: ")

newstr = ""
for ch in string:
  newstr = newstr + ch + char
print(newstr)

This is almost correct. How can we change the above to get the first char in the newstr?

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.