Skip to main content
Contents
Dark Mode Prev Up Next Scratch ActiveCode Profile
\(\newcommand{\N}{\mathbb N}
\newcommand{\Z}{\mathbb Z}
\newcommand{\Q}{\mathbb Q}
\newcommand{\R}{\mathbb R}
\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.3 Assessment: Writing Loops
Subgoals for Writing a Loop.
Determine purpose of loop
Pick a loop structure (while, for, do_while)
Define and initialize variables
Determine termination condition
Invert termination condition to continuation condition
Update Loop Control Variable to reach termination
Exercises Exercises
1.
Q1: Given the following code segment:
x = 1
while ___:
if x % 2 == 0:
print(x)
x = x + 2
Consider the following conditions to replace
___
in the code segment:
For which of the conditions will nothing be printed?
2.
Q2: Given the following code segment which is intended to print the number of integers that evenly divide the integer input_val. (You may assume that input_val > 0.)
count = 0
input_val = int(input())
for k in range(1, input_val):
if ___:
count += 1;
print(count)
Which of the following can be used to replace ___ so that the code will work as intended?
3.
Q3: Which of the following code segments will produce the output:
k = 1
while k < 20:
if k % 3 == 1:
print(k, end=" ")
k = k + 3
for k in range(1, 19):
if k % 3 == 1:
print(k, end=" ")
k = 1
while k < 20:
print(k, end=" ")
k = k + 3
4.
Q4: What is the maximum number of times βHelloβ can be printed?
k = # a random number such that 1 <= k <= n
for p in range(2, k):
for r in range(1, k - 1):
print("Hello")
5.
Q5: Fill in the blanks in the following code to create a program that will print the prime numbers between 1 and 100 (inclusive).
for i in range(__A__, __B__):
is_prime = True
for j in range(__C__, __D__):
if i % j == __E__:
is_prime = False
if is_prime:
print(i, end=" ")
You have attempted
of
activities on this page.