Iteration: AP CSP practice
for and while loops, counting and totals. 5 questions in the style of the AP CSP exam.
Sample questions
What is displayed? In AP pseudocode, DISPLAY shows a value followed by a space, so type every displayed value on one line, separated by single spaces.
n ← 1
count ← 0
REPEAT UNTIL (n > 50)
{
n ← n * 3
count ← count + 1
}
DISPLAY(n)
DISPLAY(count)This is practice in the style of the end-of-course written response questions, which ask about code from your own Personalized Project Reference. Use the example program shown. Consider the loop for w in words in the main part of the program. Explain how many times the loop body runs and what happens each time. Then explain what would change if a fifth word were added to the list.
import random
words = ["planet", "orbit", "comet", "galaxy"]
def scramble(word, swaps):
letters = list(word)
for i in range(swaps):
a = random.randint(0, len(letters) - 1)
b = random.randint(0, len(letters) - 1)
letters[a], letters[b] = letters[b], letters[a]
return "".join(letters)
score = 0
for w in words:
print(scramble(w, 3))
guess = input()
if guess == w:
score = score + 1
print("Score:", score, "out of", len(words))