Intro to
Programming
with Python

Fall 2010
course
navigation

sep 14

Questions ?

chapter 2 and 3

loops
interest_rate = 3.0 # percent start_amount = amount = 100.00 periods = 10 for i in range(periods): amount = amount * (1 + interest_rate/100.0) print amount, " at ", \ interest_rate, "% ", \ periods, " times is ", amount # (The "\" character at the end of a line # continues it on the next line.)
data types
float numbers are approximate - finite number of bits for storage
# (This is with older versions of python) >>> 0.3 0.29999999999999999
but in python, integers grow as needed ... and become another type
>>> 2**10, 2**20, 2**30, 2**40 (1024, 1048576, 1073741824, 1099511627776L)
(Notice the "L" at the end of the last number: that's a new "long" type.)
Discussion: why is the switch near 2**30 ? why not always use "long" types for integers? why have different storage for floats and ints?

math library

First a bit about names, namespaces, and dir()
$ python >>> dir() # what ['__builtins__', '__doc__', '__name__'] >>> dir(__builtins__) ... long list of built-in things ... >>> from math import * >>> dir() ['__builtins__', '__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
The math functions like sin(), cos(), sqrt(), aren't available in python by default. Instead, you must "import" them from a "module" called "math".
The book does this instead :
>>> import math >>> math.sqrt(3.0)
which leaves things from the math module with "math." before their names. If you do things that way, sin(pi/2) is math.sin(math.pi/2).

accumulating results in a loop

sum = 0 numbers = [1, 10, 20, 18, 17, 34, 22] for number in numbers: sum = sum + number print "The sum is ", sum

chapter 4 : strings

input

This fails:
# THIS WON'T WORK name = input("What is your name? ") print "You said ", name
because the input() command treats what you typed as if it were python code. (Oops).
Instead, you should do this:
name = raw_input("What is your name? ") print "You said ", name

playing with strings

codes

string operations summary

"this " + "that" # concatenate "x" * 10 # replicate "This is a string"[0:3] # substrings len("string") # how many characters? for char in the_string: # loop over characters # lots more import string # grab a bunch of 'em dir(string) # list all the string.yyy() functions dir("xxx") # what the the "xxx".method() things? # conversions x = float("32.3") # convert string to float y = int("101") # convert string to int z = str(xxx) # convert anything to string eval("1+2") # intepret string as python expression

formatting

Probably for next time ...

file processing

ditto
http://cs.marlboro.edu/ courses/ fall2010/python/ notes/ sep_14
last modified Tuesday September 14 2010 12:44 am EDT