CSE 163
Introduction to Python II
Strings and Lists
Suh Young Choi
🎶 Listening to: Across the Spider-Verse Soundtrack�💬 Before Class: Read any good books lately?
This Time
Last Time
2
Quick Announcements!
3
Recap: Lesson
Strings
Lists
Documentation
None
4
String Methods vs. len
Call functions on strings using syntax:
This is not true for len (or other built-in Python functions):
This asymmetry is annoying, but you have to get used to it!
5
s.function(params)
len(s)
Strings
vs.
Lists
6
s = 'hello world'
# Length
len(s) # 11
# Indexing
s[1] # 'e'
s[len(s) - 1] # 'd'
# Looping
for i in range(len(s)):
print(s[i])
for c in s:
print(c)
l = ['dog', 'says', 'woof']
# Length
len(l) # 3
# Indexing
l[1] # 'says'
l[len(l) - 1] # 'woof'
# Looping
for i in range(len(l)):
print(l[i])
for word in l:
print(word)
Function comments
Function comments are the best way for others to know what your code does!
7
def sum_what(nums):
“””
Takes in a list of
numbers and returns the
sum of those numbers.
“””
total = 0
for i in nums:
total += i
return total
def sum_how(nums):
“””
Takes in a list of numbers,
then calculates the sum of
all numbers using a for loop
to iterate through all numbers.
“””
total = 0
for i in nums:
total += i
return total
Anatomy of a Function
8
function �header
parameters
function �body
function call
return statement
Anatomy of a Function (updated!)
function �header
9
parameters
function �body
return statement
function call
type annotations
doc-string comment
None
10
def increment(x):
if x < 0:
return None
else:
return x + 1
if increment(-1) is None:
print('Failed')
What are you still curious about?
11
“
Group Work:
Best Practices
When you first working with this group:
Tips:
12
Next Time
Quiz Section
Lesson
Before Next Time
13