An Intro to
Programming
with Python

Fall 2006
course
navigation

sep 22

Finish talking about chapter 4.
Last time we talked about subscripts. Any questions about that?
For those of you who've seen programing before, notice that we're learning how to do some pretty tricky things ... but we don't have conditionals
x = raw_input('what is x? ') # type, say, 1+2 type(x) # x is a string x = eval(x) # treat 'x' as a python line type(x) # now it's a number (3)
iteration through a string :
a = 'This is a string' for char in a: print 'The ASCII for "' + a + '" is ' + str(ord(a))
Typing lists on more than one line is OK. Usually the indentation here is used to make it look nice. Python can tell from the unclosed [ that the list isn't done.
b = [ 1, 2, "three", 'four', 5, 6 ]
ASCII to character and character to ASCII: ord() and chr()
print ord('a') print chr(97) import string string.split('this is a string') # gives ['this', 'is', 'a', 'string']
or
'this is a string'.split()
Other string functions
string.lower() string.upper() string.replace(this, that) index = string.find(sub-string) string.split(regex) import string help(string) list('hello there')
mod arithmetic and secret codes : substitution and rearrange
What does this do?
>>> def shift(char, n): ... one_to_26 = ord(char) - ord('a') + 1 ... shifted = one_to_26 + n % 26 ... return chr( ord('a') + shifted)
Can you put it in a loop?
Can you rearrange a string of letters?
Can you implement somethin like this cipher?
the quick brown fox jumps over the lazy dog hel lohel lohel loh elloh ...
where we write 'hello' over and over and use those letters to figure out how far to skip?
(Spaces will be an issue; let's say we put the message in blocks of 5 characters and leave out all spaces.)
Formatting strings:
<template string> % ( <values> ) "The answer is %0.2f, %0.2f" % (23.2332, 4)
File input/output
in = open('filename.txt', 'r') whole_file = in.read() # or line = in.readline() # or line_list = in.readlines() out = open('newfilename.txt', 'w') out.write('This is stuff to put') # must provide newlines as "\n" explicilty

in class

a crypto transposition cipher
>>> old = "abcde" >>> new = "" >>> for i in range(5): ... char = old[mixup[i]] ... new = new + char ... >>> new 'bdace' # abcd rearranged
a crytpo substitution cipher
>>> def shift(char, n): ... ascii = ord(char) ... zero_to_25 = ascii - ord('a') ... shifted = ( zero_to_25 + n ) % 26 ... return chr( ord('a') + shifted ) ... >>> shift('a', 2) 'c' >>> shift('z', 10) 'j' >>> def encode(string): ... new = '' ... for char in string: ... new = new + shift(char, 7) ... return new ... >>> encode('hello') 'olssv' >>> encode('jimmahoney') 'qptthovulf' >>>

http://cs.marlboro.edu/ courses/ fall2006/python/ notes/ sep_22
last modified Friday September 22 2006 11:27 am EDT