For and While Loops

Question Click to View Answer

What does the following print to the console.

sum = 0
counter = 0
numbers = [1, 2, 3, 4]
while counter < len(numbers):
  sum = sum + numbers[counter]
  counter = counter + 1
print(sum)

10 is printed.

The sum and counter variables are initially set to zero. The while loop is used to iterate over every item in the numbers list and update the sum variable. The counter variable is incremented for each loop iteration.

What does the following print to the console.

word = ""
counter = 0
letters = ["c", "a", "r"]
while counter < len(letters):
  word = word + letters[counter]
  counter = counter + 1
print(word)

"car" is printed.

The word variable is initially set to the empty string and a while loop is used to iterate over every item in the letters list. Each letter is appended to the word variable and the counter is incremented for each loop iteration.

What does the following print to the console.

sum = 0
counter = 0
numbers = [22, 55, 111, 555]
while numbers[counter] < 100:
  sum = sum + numbers[counter]
  counter = counter + 1
print(sum)

77 is printed.

This while loop sums all the numbers in the list until it hits a number that's greater than 100. In this example, the loop sums 22 and 55 and then exits when it hits 111.

What does the following print to the console.

result = 0
numbers = [2, 4, 6]
for num in numbers:
  result = result + num
print(result)

12 is printed.

The for loop iterates over every element in the numbers list and sums them in the result variable.

for loops are similar to while loops, but they allow for less typing because counter variables aren't needed.

What does the following print to the console.

word = ""
letters = ["t", "r", "a", "i", "n"]
for letter in letters:
  word = word + letter
print(word)

"train" is printed.

The for loop iterates over ever letter in the letters list and appends each letter to the word variable. The resulting string is then printed.