WEEK02: numbers and strings
 M: review, accumulator pattern, main(), debug-as-you-go

LAB1: due Tuesday
QUIZ1: Friday (see the quiz topics page on the schedule)
SIGN UP for 10-minute interview

accumulator pattern:

 - suppose I have a large bucket and I ask everyone in the class
   to put all of their money in the bucket? This is the idea of
   an ACCUMULATOR: start with an "empty" variable (the bucket) and
   repeatedly add to what's in the bucket

 - in python (and other languages) you can add to what's already
   stored in a variable like this:

       x = x + 1

   this looks odd if it's a mathematical statement, but it's not -- it's
   an assignment. Take whatever is stored in the variable x, add one to
   it, then assign the result back to the variable x

 - here's how you would sum up 10 numbers the user enters:

sum = 0
for i in range(10):
  usernum = input("enter a number: ")
  sum = sum + usernum

print "The sum of those numbers is: ", sum

# ------------------------------------------------------------------ #


Calculate the Gamma function of n, where

   Gamma(n) = (n - 1)! = (n-1)*(n-2)*...*2*1

J. Knerr
Spring 2011
# ---------------------------------------------- #

def main():
  """get n, calculate G(n), output results"""

  print "Gamma(n) calculator...please enter n\n"

  n = input("n: ")
  result = 1
  for i in range(2,n):
    result = result * i  # looks like an ACCUMULATOR!!!

  # use print formatting to output results
  print "\nGamma(%d) = %d" % (n, result)

# ---------------------------------------------- #



n = input("n: ")
x = 1
for i in range(2,n):
  x = x * i
print x

 - they actually do the same thing, but one has nice comments
   and good variable names, and will be much easier to understand
   at a later date, should you ever need to revise it

# ------------------------------------------------------------------ #

DEBUG-AS-YOU-GO: type in a line or two of python code, then
test it out (don't type in your whole program, then try to run it).

Programs are much easier to debug if you just add one or two
lines, then test them to make sure they work.

# ------------------------------------------------------------------ #

YOUR TURN: can you write this program???

$ python sum_numbers.py 

  Let's sum some numbers. Please enter a start and
  a finish number, and I'll sum all numbers from start 
  to finish...

 start: 2
finish: 6

The sum of numbers from 2 to 6 = 20

# ------------------------------------------------------------------ #

Since python allows the use of addition with strings and characters,
you can also do an accumulator with strings. How would you use an
accumulator to do this?

$ python revstr.py 
text: we love comp sci!!
!!ics pmoc evol ew

(reverse a string typed in by the user)