What is the result of executing the following code?
number = 5
while number <= 5:
if number < 5:
number = number + 1
print(number)
The program will loop indefinitely
Correct! This code loops while number is less than or equal to 5. number only increments if it is less than 5, and it’s originally set to 5, so ’number’ never changes.
The value of number will be printed exactly 1 time
Incorrect! This would be true if line 3 said "if number <= 5:". Try again.
The while loop will never get executed
Incorrect! This would be true if number was initialized as a number larger than 5 to start. Try again.
The value of number will be printed exactly 5 times
Incorrect! This would be true if number was initialized as 0. Try again.
2.
What will the following code print?
counter = 1
sum = 0
while counter <= 6:
sum = sum + counter
counter = counter + 2
print(sum)
12
Incorrect! This would be true if counter was initialized as 0. Try again.
9
Correct! This loop executes 3 times. After the first loop, sum is 1 and counter is 3. After the second loop, sum is 4 and counter is 5. After the third loop, sum is 9 and counter is 7.
7
Incorrect! This is the value of counter, but this code prints the value of sum. Try again.
8
Incorrect! This would be the value of counter after the loop if counter was initialized as 0. Try again.
3.
What will be printed by the following code when it executes?
sum = 0
values = [1,3,5,7]
for number in values:
sum = sum + number
print(sum)
4
Incorrect! This would be true if line 4 said sum = sum + 1. Try again.
0
Incorrect! sum increases every iteration of the loop. Try again.
7
Incorrect! This would be true if line 4 said sum = number. Try again.
16
Correct! This adds up the numbers in values and prints the sum.
4.
What is the last thing printed when the following code is run?
number = 0
while number <= 10:
print("Number: ", number)
number = number + 1
Number: 10
Correct! Since this while loop continues while number is less than or equal to 10, the last iteration of the loop will print Number: 10.
Number: number
Incorrect! Because number is an variable, the print statement will print its value, not its name. Try again.
Number: 0
Incorrect! Although number is initialized as 0, it increments each iteration. Try again.
Number: 11
Incorrect! This would be true if number was incremented before each print statement instead of after. Try again.
5.
What does the following code print?
output = ""
x = -5
while x < 0:
x = x + 1
output = output + str(x) + " "
print(output)
5 4 3 2 1
Incorrect! x is initialized as -5, not 5. Try again.
-4 -3 -2 -1 0
Correct! The value of x is incremented before it is printed, so the first value printed is -4.
-5 -4 -3 -2 -1
Incorrect! x is incremented before it is printed. Try again.
This is an infinite loop, so nothing will be printed
Incorrect! x increases each loop and will eventually be positive. Try again.
6.
What are the values of var1 and var2 that are printed when the following code executes?