Thu Sep 17
Lots to cover today - let's jump in.
about the homework due last Tuesday
I have given feedback on all the homework that you have
submitted. Looks like generally you're working and
making good progress through the material.
Please look at your homework to see what I said.
Be clear that :
- The point isn't to get everything perfectly correct - instead it's to explore these ideas, practice manipulating the data, and dig in to the documentation.
- Being stuck and/or confused is OK. Pay careful attention to what the blockage is, and see if there's a away around it - that's what you're really trying to learn.
Specific notes about your work :
1. Please, please, please quote your sources. I can't say that enough. For me to help you, I need to understand just what you know, and how you're learning new stuff.
2. Now that you have seen my examples, please follow that format: comment blocks at the start, and sample output.
3. Some of you are using python constructs and syntax that is more sophisticated than what we've covered in class. That's OK if you understand it. (Though it may be an interesting exercise to do the problems using only the material we've done so far.) However, if you're copy/pasting something you found online without knowing what it is ... not so good.
some non-idiomatic-python things I saw in your homework
Number = 1
# By convention python saves upper case for objects - not variable names. Should be "number = 1"
a=3
# More readable in most cases is to put spaces around the operators: "a = 3"
while 1:
pass
# This is how C programmer code. In python it would be "while True:" We'll get there.
formatting
For most of you, I have reformatted what you submitted to make it look nicer.
Click the "edit" button in your submission to see what I did, so that you can do it yourself next time.
Also, if you upload a .py file, then hitting that url with _html at the end will usually make it look pretty on cs.marlboro.edu ...
about the homework due next Tuesday
It's been posted.
These exercises are building
on the material we have already done (loops, accumulator pattern, etc)
and the new ideas (strings, ascii, files). We already have some powerful tools
and can do some tricky stuff ...
It's OK if you get stuck or are not sure where to start.
Here are some ideas that might help you get unstuck.
- Is there another thing you can do that's similar to this?
- Google keywords or questions. If you find something and it helps and you use it, then
- 1. Put the url you got it from into your submission (i.e. quote your sources)
- 2. Make sure you understand how it works - play around with it a bit.
- Print everything you can think of, everywhere, to ensure it is all doing what you expect.
- Slowly add tiny bits of code, seeing the program run differently each time.
- Writing too much code without running it is a "really bad idea".
- Ask a classmate, or Dylan, or Logan, or me, for a hint or specific help.
back to strings
(Here we'll pick up from where we were
last time ... getting back to the cipher
stuff as time allows.)
Any questions from the reading or anything so far?
string operations summary
There are many ways to manipulate strings in python.
'this ' + 'that' # concatenate
'x' * 10 # replicate
'This is a string'[0:3] # substrings; 'Thi'
len('string') # how many characters?
for char in the_string: # loop over characters
print char, ' is ', ord(char) # ... and do something with each
# 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(anything) # convert anything to a string
eval("1+2") # evaluate string as python expression; return result
Discuss the name.method(arg1, arg2) convention we just started seeing.
We'll be getting lots more of that.
And remember the dir() trick to see what
.method() things there are for different things in the language.
More practice with string manipulations.
import string
text = "This is some text."
text_list = list(text) # ['T', 'h', ...]
test_list2 = string.split(text, '') # same thing
back_to_text = string.join(text_list, '')
hello_there = "hello" + " " + "there"
number = ord('h')
letter = chr(number)
word_dashes = 'one-two-three'
word_list = string.split(word_dashes, '-') # ['one', 'two', 'three']
word_commas = string.join(word_list, ',') # 'one,two,three'
Aside :
There are actually three 'places' that the string functions live, which can be confusing :
>>> number = ord('h') # built-in function
>>> import string
>>> string.upper('hello') # within the string module
Or just this :
>>> 'hello'.upper() # (!)
The last form we haven't talked about yet, but will do lots more with later.
(This is actually "object-oriented" programming, in which we think
of the string 'hello' as an "object" and upper as one of its "methods".)
Many of the string manipulations are available in both the string module
and as methods of strings. To see the difference
>>> import string # load the string module
>>> dir(string) # functions and variables in the string module
>>> dir('hello') # names that can be used as 'hello'.name
converting between lists and strings
Some operations are easier when working with a list
than a string. Python does allow you to convert between them.
>>> abc_string = 'abc'
>>> abc_list = list(abc_string) # ['a', 'b', 'c']
Going the other way isn't quite as easy.
>>> str(abc_list) # what do you think this is?
The python function is "join". Unfortunately,
it lives several places ... and has several calling conventions.
Here's the one I recommend.
>>> import string
>>> string.join(abc_list, "") # the 2nd arg is what to join with
a few class exercises
1. Can you change the characters in a string
to uppercase, turning "word" into "WORD"?
>>> text = "this"
>>> answer = ""
>>> for letter in text:
... answer = answer + chr( ord(letter) - 32 )
...
>>> answer
'THIS'
or
>>> text.upper()
'THIS'
2. Can you do that to the first letter of
a word, changing "this" to "This" ?
>>> text = 'this'
>>> chr(ord(text[0]) - 32) + text[1:]
or
>>> text.title()
3. Can you reverse a word, changing
"hello" to "olleh" ?
The trick is to append the new letters
to the left side as we grow the answer.
>>> text = 'this'
>>> answer = ""
>>> for letter in text:
... answer = letter + answer
...
There are functions built into python (and the string module)
that can do these things ... or help with them.
Or you can do them yourself with loops, the accumulator pattern,
ord(), and chr() ...
text formatting
Making the output look nice.
There are several ways to do this within python:
the old way (in your text), and the new way (recommended).
In both cases, markers are put within a string to
indicate where values should go, and then variables
are "interpolated" into the string in some given
format. The details get messy.
the old way : ("x=%f" % 3)
I'll mention this and then (mostly) ignore it.
print "Compare %f and %0.20f \n" % (3.14, 3.14)
Here the "%" symbol is placed between (a) the string with its markers
and (b) a sequence of the values to be interpolated.
The funky symbols within the string (%i, %f, %d, %s) give the format (integer, float, decimal, string).
the new way : "x={}".format(3)
The python language has been transitioning to a new syntax
for string formatting, the .format() string method and {}
for interpoloation.
The new version looks like this :
print "Compare {} and {:0.20} ".format(3.14, 3.14)
This is what you should do. For the details see the docs.
Files
A 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")
# In that last line :
# '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") # \n is newline
summary of strings, text, files
Putting all this together you get a very typical program :
- open a file
- read stuff in (typically text or numbers)
- do something to it (put it into a secret code, for example)
- write it back out
Here are some programs that we might try to
write and/or discuss in class, if time allows.
in class 1 : rot13 file conversion
- see wikipedia:rot13
- Ask for input file name
- create file with same name, but 'rot13_' on front.
- Read input to a string.
- In a loop, convert (and store) the thing to its rot13 version
- Output new string to new file
in class 2 : write a program that counts the characters in a file.
- Discuss where to start ...
in class 3 : secret decoder ring : translating words into codes by adding an offset.
- We can get the number for (say) 'a' with ord('a')
- We can add an offset to the number, wrapping around at 'z' with the "i % 26" mod arithmetic operator.
- And then translate from numbers back to letters with chr()
- Do this letter by letter, accumulating the result.
- The code is something like this : cipher.py .
(You are welcome to use that code as a starting point
to think about this week's assignment. But if so,
do list it as source.)
The assignment for next week has lots of practice with this sort of stuff ...