Python loops quiz question

Hi there,

Just been going through the quiz questions to recap python knowledge. One question in the python loops quiz makes no sense to me whatsoever. Please advise on the following question.

Fill in the blanks to produce yellow in the console.

value = "none"
colors = ["violet", "blue", "green", "yellow"]
for item in colors:
 value = item


How does yellow get printed from value which has “none” assigned?

In the way that’s written the original object that was assigned to value will be forgotten and the name value is assigned to a new string inside the loop. Since we’re looping this assignment happens more than once. Each time the name, “value”, is reassigned.

Ignoring the loop for a moment it’s no different than the following-

a = 'egg'
a = 'hat'
Out: hat

Python’s loops are not like functions where names defined inside the function are set for garbage collection once the function returns to the caller. They exist in the same scope as the rest of the code block they are part of. This may be different to other languages you have used.


that is a very easy to understand explanation thank you. :relaxed:

1 Like