Oct 02: Prac3, for Statements
Learning Objectives
After today's class, you should be able to:
- Explain the syntax and meaning of a for statement.
- Describe examples of how a for loop can be used.
- Predict how
range()works given 1, 2, or 3 arguments - Use for loops to obtain information from containers
Reminders¶
- Read Week 7 Reading and Activities – ideally:
- 1st half before Friday
- 2nd half before Monday
- Submit HW 7 – ideally:
- 1 and 2 before Friday
- 3 and 4 before Monday
HW6 Debrief¶
- Testing with
doctestReal Python Tutorial random.randint()versusrandom.random()if-elif-elseinside of awhileloop- Importing functions from another module
Practice Quiz 3¶
- Two portions to the quiz: written and coding
- Log in as
student - Start exam recording
- Log in to Canvas only
- Raise your hand when complete with Canvas written portion
- Open Thonny for coding portion only
- Submit code through Canvas (will go to Gradescope)
- Log out when finished
POGIL Activity¶
- For loops
- If you are absent today, complete this activity at home
- Bring your completed activity to class or office hours
Example Code¶
Model 1
print("hello")
for x in [2, 7, 1]:
print("the number is", x)
print("goodbye")
Model 2
range(5)
list(range(5))
x = range(3)
print(x)
print(list(x))
list(range(5, 10))
list(range(-3, 4))
list(range(4, 10, 2))
for i in range(5):
print(i)
for c in "Hi!":
print(c)
names = ["emma", "liam", "aisha", "mateo", "sofia", "ravi"]
for i in range(len(names)):
name = names[i]
# replace element at index i
names[i] = name.capitalize()
prices = [19.99, 6.34, 1.00, 12.79, 2.50]
Bonus Work¶
1. Given a string, print each uppercase letter along with its index.
Ex: print_upper("James Madison Computer Science") should print:
J at 0
M at 6
C at 14
S at 23
count_words("mat the cat sat on the mat") should return:
{'mat': 2, 'the': 2, 'cat': 1, 'sat': 1, 'on': 1}
Min, Max, Sum¶
- the built-in functions
min(), max(), sum(). The implementation of these require a loop. The code for these may look something like this:
def my_min(sequence):
result = sequence[0]
for value in sequence:
if value < result: # found new minimum
result = value
return result
def my_max(sequence):
result = sequence[0]
for value in sequence:
if value > result: # found new maximum
result = value
return result
def my_sum(sequence):
result = 0
for value in sequence:
result += value # add running total
return result
if __name__ == "__main__":
print("min:", my_min([13, -5, 100, 0, 77]))
print("max:", my_max([13, -5, 100, 0, 77]))
print("sum:", my_sum([13, -5, 100, 0, 77]))
- What happens with this line of code:
sum(grades)/max (grades)? How many loops are executed?
3. Find the index of the maximum value in a list.
Ex. index_max([13, -5, 100, 0, 77]) returns 2.
4. Count how many characters in a string are digits.
Ex. count_digits("Today is 10/03/2023!") returns 8
Indexing¶
- Sometimes a loop needs to look at
index [i + 1]. - In that case, the range should end at
len(s) - 1.
def is_sorted(seq):
for i in range(len(seq) - 1):
if seq[i] > seq[i + 1]:
return False
return True
if __name__ == "__main__":
print("yes sorted:", is_sorted([1, 5, 10, 13, 16]))
print("not sorted:", is_sorted([1, 5, 13, 16, 10]))
5. Write a function, two_in_row, that returns True if two consecutive values are equal.
Ex. two_in_row(["Pizza", "Soda", "Soda", "Candy", "Salad"]) returns True.
6. Write a function, three_in_row, that returns True if three consecutive values are equal.
Ex. three_in_row(["Apple", "Banana", "Cherry", "Cherry", "Cherry"]) returns True.