Outline for April 15, 2009
Reading
: §4.1–4.3
Guest Lecturer
: Justin Cummins
Sequences
Accustomed to use in for loops (
for i in range(5):
)
Sequences are a series of values in a particular order
In Python predominantly strings and lists but also sets and tuples
Strings
Sequence of characters (characters are strings of length 1)
Special characters: newline ‘\n’ and tab ‘\t’
Strings are immutable (also ints, floats, long ints); really important for functions
Lists
Sequence of values (ints, floats, long ints, strings, other lists, etc.)
Denoted by square brackets “[]” with values separated by commas
Lists are mutable
raw_input()
Does not make assumptions of input type
Input always returned as string
Basic string operations
+, concatenation for like types (strings, lists)
*, repetition repeats given value
len() returns length of sequence
Indexing, var[position]
Count from 0 to len(var)−1
Position can be a negative number to count from right
Position/index illustrated in
str_array.py
Assignment with indexing, only works for lists because they are mutable
Slicing, var[start:end]
Value at index end not included in slice
If omitted, starting value defaults to 0 and ending value defaults to last index + 1
Can use negative index
Type conversion
str(val) attempts to convert val to a string
list(sequence) attempts to convert sequence to a list
Program to assign letter grade when given score from 0 to 5:
score.py
Program to square each value in a list:
squarelist.py