Intro to
Programming
with Python

Fall 2010
course
navigation

sep 16

Questions?
#aside for davey: numbers = [11 12, 13] letters = ['h', 'i'] double = map(lambda x: 2*x, numbers) # gives [22, 24, 26] concat = reduce(lambda x,y: x+y, ['h', 'e', 'l', 'l', 'o']) # gives "hi" # but last is better as ''.join(letters)
Documentation links on resources page :
Finish chap 4:
1. bunch of string operations; see pg 48 of Zelle. import string text = "This is some text." text_list = list(text) # ['T', 'h', ...] back_to_text = string.join(text_list, '') hello_there = "hello" + " " + "there" number = ascii('h') letter = chr(number)
2. Making the output look nice: text formatting : %i, %f, %d, %s within format strings, using "%" operator on strings. print "Compare %f and %0.20f \n" % (3.14, 3.14)
3. Files
I file is essentially a list of lines. Once you've "opened" one, you can read from it and/or print to it.
inputfile = open("filename_here", "r") # 'r' for 'read' access', i.e. input, 'w' for 'write access', i.e. output # Input: use one of these three : whole_file = inputfile.read() next_line = inputfile.readline() array_of_lines = inputfile.readlines() outputfile = open("other_filename_here", "w') outputfile.write("this will be the first line in that file. \n")
4. ascii : numeric values for 1 byte characters;
Putting all this together you get a very typical program :
Example: do file conversion rot13 in class
Here's what we created in class : # rot13.py # Example of rot13 text transform # Jim M , Sep 16 2010 (in class) # import string def main(): # 1. Get the text to be transformed. text = raw_input("What is the (lowercase) word? ") # 2. Convert the text to rot13. rot13_text = "" for char in text: number = ord(char) - ord('a') # print " debug: number = ", number rot13_number = (number + 13) % 26 # print " debug: rot13_number + ", rot13_number new_char = chr(rot13_number + ord('a')) # print " debug: new_char = '%s' " % new_char rot13_text = rot13_text + new_char # 3. Output the text. print "rot13='%s'" % rot13_text main()
http://cs.marlboro.edu/ courses/ fall2010/python/ notes/ sep_16
last modified Thursday September 16 2010 11:19 am EDT