knerr cs21 notes...

back to schedule

WEEK02: numbers and strings
---------------------------------------------------------------
 M: review, accumulator pattern, debug-as-you-go, math module, print formatting

LAB1: due Tuesday
QUIZ1: Friday (do the practice quiz)
/home/jk/inclass/blastoff.py (review)

accumulator pattern:

sum = 0
for i in range(10):
  sum = sum + i
print sum

average grades input by the user:

$ pwd
/home/jk/inclass
$ cat grade_average.py 

ngrades = input("please enter # of grades: ")
# print ngrades

sum = 0
for i in range(1,ngrades+1,1):
  grade = input("grade " + str(i) + ": ")
  sum = sum + grade
  # print i, sum

ave = sum / float(ngrades)
print "ave = " + str(ave)

print "\n\nthe ave of those %d grades is %0.6f\n\n" % (ngrades,ave)

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

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 run it).

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

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

MATH MODULE:

  import math
  help(math)

  or

  from math import *

  try each of these in the python interactive shell and see how 
  they are used:

$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'math']
>>> math.pi
3.1415926535897931
>>> math.pi * 2.0
6.2831853071795862
>>> sin(1.0)
Traceback (most recent call last):
  File "< stdin > ", line 1, in < module >
NameError: name 'sin' is not defined
>>> math.sin(1.0)
0.8414709848078965
>>> 

$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> from math import *
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> sin(1.0)
0.8414709848078965
>>> math.sin(1.0)
Traceback (most recent call last):
  File "< stdin > ", line 1, in < module >
NameError: name 'math' is not defined
>>> pi
3.1415926535897931
>>> 

PRINT FORMATTING:

 - use %d, %f, and %s in your strings to better control the output format
 - here are some examples:

>>> i = 10
>>> x = 3.14159
>>> s = "Pizza"  
>>> print "I love %s" % (s)
I love Pizza
>>> print "i = %d, x = %0.3f" % (i,x)
i = 10, x = 3.142