Download - Last Week if statement print statement input builtin function strings and methods for loop
Last Week
• if statement
• print statement
• input builtin function
• strings and methods
• for loop
This Week• Practice with string methods and for
loops• Doctests• Conversion specifiers• New type list
– methods– Nested lists– Looping through a list– Looping using range
Doctests
Why do we use an example in our docstrings?
– To show the user how to call our function
– To ensure our function works properly
We can test our function by using the doctest module.
Docstringsimport doctest
def count_spaces(s):
‘’’(str) -> int
Return the number of spaces in s as an int.
>>>count_spaces(‘’)
0
>>>count_spaces(‘ ‘)
1
>>>count_spaces(‘there are several spaces here.’)
4
’’’
Doctestsdef count_spaces(s):
count = 0
for char in s:
if char == ‘ ‘:
count += 1
return count
if __name__ == ‘__main__’:
doctest.testmod()
# or for more details use
doctest.testmod(verbose=True)
What do these do? Let’s try it!
Visiting the Items in a String S
Printing out the characters of the string
English:for each char in S
print the charPython:
for char in S:
print(char)
Notes:char is a variable namefor and in are Python key words
for loopsFormat:
for variable in string:
statements
Example with strings:
name = ”Edward”
new = “”
for letter in name:
new = letter + new
print(new)
Strings Using Conversion SpecifiersWe sometimes would like to insert values of variables into strings:A1 = 60A2 = 75A3 = 88
We would like: ‘The average of 60, 75 and 88 is 74.33.’
How do we print this with our variables?
>>>print(‘The average of’, A1, ‘,’, A2, ‘ and ’, A3, ‘ is ’, (A1+A2+A3)/3)
Does this work?
Strings Using Conversion SpecifiersWe displayed:‘The average of 60 , 75 and 88 is 74.33333333333333 .’
Q. What’s wrong?A. Spacing is wrong around commas and periods.
We have many more decimal places than wanted.
Q. How can we fix it?A. Use conversion specifiers.
>>>print(‘The average of %d, %d and %d is %.2f’ %(A1, A2, A3, (A1+A2+A3)/3.0))
The average of 60, 75 and 88 is 74.33.
Common Conversion Specifiers
%d display the object as a decimal integer
%f display the object as a floating point with 6 decimal places%.2f display the object as a floating point with 2 decimal places%s display the object as a string
Q. What else do we use % for?
A. Modulus. We say that % is overloaded.
Way to store many variables, e.g.,
students = [“Abby”, “Bob”, “Harry”, “Sara”, “Don”]
grades_list = [85, 80, 82, 84, 83]
misc = [“Kaya”, 2006, “July”, 20, True]
students[0] = ?
students[3] = ?
grades_list[2] = ?
grades_list[5] = ?
Lists
“Abby”“Sara” 82
error
Lists cont…
grades_list = [85, 80, 82, 84, 83]
grades_list[2] = 86
grades_list.append(90)
grades_list == ??
Functionslen(grades_list) outputs…
max(grades_list) outputs…
min(grades_list) outputs…
sum(grades_list) outputs…
[85, 80, 86, 84, 83, 90]
6
90
80
508
work for strings too
students = [“Abby”, “Bob”, “Harris”, “Sara”, “Don”]
students.sort()
[“Abby”, “Bob”, “Don”, “Sara”, “Harris”]
students.insert(2, “Charlie”)
[“Abby”, “Bob”, “Charlie”, “Don”, “Sara”, “Harris”]
students.append(“Kaya”) has the same result as
students.insert( ???? , “Kaya”)
Lists -- Methods
student.insert(len(students), “Kaya”)
student_grades = [[‘99887766’, 72], [‘111222333’, 90],
[[‘99118822’, 84]]
student_grades[0] ==
student_grades[0][0] ==
student_grades[1][0] ==
student_grades[2][1] ==
Nested Lists -- Lists of Lists
listlistlist
[‘99887766’,72]
‘99887766’
‘111222333’
84
??
??
??
??
Slicing Lists or StringsIdea: Grab part of a list aka a slice of a list.
countries = [‘Canada’, ‘France’, ‘China’, ‘Italy’, ‘India’] 0 1 2 3 4
countries[0:2] ==
countries[3:] ==
countries[:4] ==
countries[s:t] means:
• start at index s
• include all list items up to but not including item t.
[‘Canada’, ‘France’, ‘China’, ‘Italy’]
??
[‘Italy’, ‘India’]??
[‘Canada’, ‘France’]
??
Visiting the Items in a List L
Printing out the list
English:for each item in L
print the itemPython:
for item in L:
print(item)
For Loops -- RevisitedWant to print the numbers from 0-100.
for num in [0, 1, 2, 3, 4, …, 99, 100]:
print(num)
Is there an easier way to do this?
for num in range(0, 101):
print(num)
range(start, stop[,step]) • returns a list of integers• beginning with start to the last integer before stop.• start can be omitted and defaults to 0• step can be omitted and defaults to 1
For Loops -- RevisitedL1 = [1, 2, 3, 4]L2 = [‘A’, ‘B’, ‘C’, ‘D’]
Want to print each element from L1 followed by the corresponding element from L2.
for num in L1: print(num, ??) # How do we print the item from L2?
Loop over indices:
for index in range(len(L2)): print(L1[index], L2[index])