[Courses] [python] Lesson 3: answers to questions
Akkana Peck
akkana at shallowsky.com
Thu Jul 7 01:40:11 UTC 2011
Some comments, and answers to people's questions on lesson 3:
First, GcX had a really cool solution for the histogram problem
(and I just saw that Monique found it too):
vals = [ 0, 2, 4, 8, 16, 18, 17, 14, 9, 7, 4, 2, 1 ]
count = 0
for x in vals:
print ' * ' * vals[count]
count += 1
I'd never thought to do it that way, multiplying the '*' * vals[i].
Very cool! I had done it the same way most of you did,
starting with s = "", looping over each value to add a '*' each time.
Multiplying like GcX did avoids the need for the inner loop.
Nice one!
You don't really need count, though: you can just say print '*' * x
since x, your loop variable, will be the same as vals[count].
A lot of people used "count" variables and looped over the list of
words in their word-counting programs. That's a little longer than
the solution I had in mind, len(words), but that's okay -- looping
over the list works too. Just keep in mind that len() is available
as a fast way to check the size of any list or string.
Ehud asked a good question: "anything wrong with chaining? that is:
wordCount = string.split(" ").len()"
Nothing wrong with it at all -- it's perfectly valid in Python, and
you'll definitely see that sort of thing a lot in Python programs in
the real world.
You won't see .len() on the end like that, though -- no such thing.
It would be wordCount = len(string.split(" ")).
You have to be a little careful chaining things together, though:
if you do too much of it, you can make your programs hard to read
with lines like
lang = line[:n].split("[")[1].split("]")[0]
(I took that from a real program, /usr/bin/obm-xdg).
Tubuntu asked, "is there a "panic command" to stop "properly" a
script that loops infinitively?"
Indeed there is. At any point inside a loop, you can say "break" to
exit the loop, or "continue" to skip to the next value in the loop.
Tubuntu also asked how to log in to Moodle. You should be able to
create an account on courses.linuxchix.org. But there's nothing really
going on there right now -- we need someone who knows more about Moodle
to take the lead if we want to start using it for classes.
I'll reply to Brad and Monique's question about variable scope separately.
...Akkana
More information about the Courses
mailing list