# ITP 115 Lecture Notes - Lecture 7: Word Game, Spamalot, Master Sergeant

36 views4 pages
7 Feb 2017
School
Course
Professor

Lecture 7
1/31/17
Strings and lists
For foo in “Python”:
print(foo, end=” “)
Output → P y t h o n
Sequences have indices
o Each individual item in a sequences is automatically given an index
o Index tells which position the item is in
o 1st index is zero (0)
o Last index is number of items - 1
o Example
Word = “spamalot”
S p a m a l o t
0 1 2 3 4 5 6 7
8 letters, but last index is 7 (8-1=7)
Sequences and random access
o Using indices, we can directly access single items from a sequence
o To read a single item from a sequence, use:
[ ] operator
o Syntax
sequenceVariable[index]
Strings: Random access
msg = “spamalot”
print(msg[2])
a
print(msg[6])
o
Msg = “spamalot”
print(msg[13])
error
Index out of range
o Only valid indices of a sequence are 0 to length-1 (Python supports negative indices,
which go from -1 to -(length). This isn’t common in programming, and we won’t use it.)
o Python generates an error if you read index beyond length-1
Also called out of bounds
o Common mistake
If sequence has 5 items, which is the index of the last item
Slicing
o We can use [index] to get a single item from a sequence
o We can use slicing to get multiple items from a sequence
o Slicing works with any sequence (e.g. string, list, etc.)
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows page 1 of the document.
Unlock all 4 pages and 3 million more documents.

# Get access

\$10 USD/m
Billed \$120 USD annually
Homework Help
Class Notes
Textbook Notes