Invert termination condition to continuation condition
Write the loop body
Update Loop Control Variable to reach termination
ExercisesExercises
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:
x < 0
x <= 1
x < 10
For which of the conditions will nothing be printed?
I only
II only
I and II only
I and III only
I, II and III
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?
input_val % k == 0
k % input_val == 0
input_val % k != 0
input_val / k == 0
k / input_val > 0
3.
Q3: Which of the following code segments will produce the output:
1 4 7 10 13 16 19
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
I only
II only
I and II only
I and III only
I, II and III
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")
2
n - 1
n - 2
(n - 2) * (n - 2)
n * n
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 = False
for j in range(__C__, __D__):
if i % j == __E__:
is_prime = True
if is_prime:
print(i, end=" ")