Skip to main content
Contents Index
Search Book
Search Results:
No results.
Readability settings Prev Up Next Scratch ActiveCode Profile
title here
\(
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section 7.6 Looping and counting
The following program counts the number of times the letter “r” appears in a string:
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 rs.
Activity 7.6.1 .
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)
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.
You have attempted
of
activities on this page.