Looking for more of an understanding of "while" loops

Could someone explain and help me grasp the concept behind this “while” loop problem within the computer science practice pack > loops? (I am looking for a nice breakdown of each action within the code block):

container_weights is a sorted list of integers in ascending order. Select the Python code block that will print the elements which are smaller than the number 40 in the console.

while container_weights[index] < 40:
print(container_weights[index])
index += 1

… just trying to solidify my knowledge around the fundamentals of loops and the help would be greatly appreciated.

Thank you!

Hey there @savior_js and welcome to the forums :slightly_smiling_face:

In the future please look at formatting your code as this preserves indentation and makes it much easier to read.

To format your code simply press this button:

Than copy/paste your code between the backticks:


As you probably know a while loop runs as long as its condition, in this case container_weights[index] < 40, evaluates to True.

In the code you have posted, index would have to be assigned somewhere before the while loop could run, in this case probably to 0.

So now the loops checks the value of index in the list container_weights and, using the less than operator: <, checks to see if it is less than 40. If it is less than 40 the loop runs and that value is printed and then the variable index is incremented so that container_weights[index] is now equal to the next value within the list.

Once the loop reaches a value that is not less than 40, the loops condition is no longer True and it terminates.

container_weights = [36, 37, 38, 39, 40]
index = 0

#  Since index is equal to 0, container_weights[index] is the first value
#  in the list, or 36      /
while container_weights[index] < 40:
#                 \
#     Since this condition is true the loop runs

  print(container_weights[index])
  index += 1
#   \
#  At the end of the loop, index is incremented, setting
#  container_weights[index] equal to the next item in the list
#  or 37

# Now the condition is exaluated again, and if it is still true
# the loop runs again. 
3 Likes

Thank you very much! That made so much more sense. I will also remember to use proper formatting next time for the code post; I see the difference now.

2 Likes