0

Difference between two blocks of codes

words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 word = words[counter] while counter <= max_index: print(word + "!") counter = counter + 1 words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 why does the first block of code print out only 'Hello!" while the second prints out all the strings in the list?

19th Oct 2016, 9:59 AM
Michael Suleiman
Michael Suleiman - avatar
2 Respuestas
+ 4
Because the value of word in the first example is only set once, out of the loop. When you write word = words[counter], word doesn't become an alias for words[counter], it is simply set to the value words[counter] currently has.
19th Oct 2016, 10:21 AM
Zen
Zen - avatar
0
thanks Zen
19th Oct 2016, 2:24 PM
Michael Suleiman
Michael Suleiman - avatar