7.6. Looping and countingΒΆ
The following program counts the number of times the letter βrβ appears in a string:
Activity: CodeLens 7.6.1 (strCount)
This program demonstrates another pattern of computation called a
counter. The variable count
is initialized
to 0 and then incremented each time an βrβ is found. When the
loop exits, count
contains the result: the total number of
rβs.
- 0
- Incorrect! count is initialized to 0, but is then incremented by the for loop. Try again.
- 3
- Correct! The letter t appears 3 times in "peanut butter".
- 4
- Incorrect! The value of count is initially 0, not 1. Try again.
- Nothing, this is an infinite loop
- Incorrect! This for loop will eventually terminate because string s has a finite number of characters. Try again.
11-9-2: What is printed by the following:
s = "peanut butter"
count = 0
for char in s:
if char == "t":
count = count + 1
print(count)
There are four errors in the following code. Fix the function so it takes a string and a character as arguments and returns the count of the character within the string.
In line 2, lettercount
should be initialized to 0. In line 4, there should be a ==
, not a =
.
In line 5, the variable name should be changed to lettercount
. In line 6, the return statement should be indented.
Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.