Questions about anything?
My graphics art example is at code/homework/sep24.
Aside : mod arithmetic in python i.e. time = (17 + 10) % 24
. (How to make a number wrap around, which I use in my art example.) It's described in python's operator docs.
Aside : The python3 docs describing the built in functions.
Aside : a python3 cheat sheet
This week we're doing chapter 5, which looks at strings, lists, and files - all containers of sequential stuff. There's a lot of material in this one - I encourage you to get started early.
I'll introduce the ideas today, and we'll continue the discussion Thursday after you've had a chance to read it in the text.
The assignment for this week, due next Tuesday, will be posted soon.
Here's a summary of the topics to cover :
word[4]
, word[3:7]
"The answer is {:0.3}".format(1.23998)
numbers.append(3)
Rather than post detailed notes here, I'll either wing it or pull up the text's lecture slides for chap5 .
Notice some of the methods discussed modify objects in place, while others return a new object. Python does not do a good job of making the distinction between these two different things clear, and that can lead to errors.
Also, some list operations return iterators rather than lists ... this can also be the source of some confusion.
>>> numbers = [10, 15, 12]
>>> numbers.append(20) # modify in place; nothing returned
>>> numbers
[10, 15, 12, 20]
>>> word = "cat"
>>> word.upper() # new uppercase word returned
'CAT'
>>> word # original unchanged
'cat'
>>> foo = [1, 2, 3]
>>> print(foo.reverse())
None # What just happened?
>>> bar = ['a', 'b', 'c']
>>> print(reversed(bar))
<list_reverseiterator object at 0x7fa3e80b4eb8> # What is this?
Also notice how we can still use the accumulator patter to build up a result.
# reverse a word using the accumulator pattern
# to build it up letter by letter.
word = 'cat'
result = '' # empty string to store result
for letter in word:
# build reversed word letter by letter
result = reversed_word + letter # put each letter on the right
print(result) # 'tac'
This works too : ''.join(list('cat')[::-1])
... see if you can figure out why.
In class I showed this code which showed the accumulator pattern in two different ways.
numbers = [20, 30, 50, 1]
total = 0
for n in numbers:
total = total + n
print("The total is " + str(total))
word = "factory"
backwards = ""
for w in word:
backwards = w + backwards
print(word + " backwards is ", backwards)