0
you can omit the variable assignment in the middle
words = ["hello", "world", "spam", "eggs"] counter = 0 max_index = len(words) - 1 # this is the original code while counter <= max_index: word = words[counter] # note the name of variable assigned: word print(word + "!") counter = counter + 1 # Cutting out the middle variable while counter <= max_index: # word = words[counter] note this line is now commented out print(words[counter] + "!") # the call to variable word has been changed to words counter = counter + 1 # this should should result in the same output
4 Respostas
+ 3
wolf in the first example you are just creating a copy and printing the copy, so there is no problem you can do it all you want
+ 3
If you run both code samples in one file in a single run, the first code will print a result. Then coming to the second code, the while condition does not match, because counter has reached value 4 from the first code. It should be initialized again with 0. Then the second code does also print the result:
words = ["hello", "world", "spam", "eggs"]
counter = 0
max_index = len(words) - 1
while counter <= max_index:
word = words[counter] # note the name of variable assigned: word
print(word + "!")
counter = counter + 1
counter = 0 # this line is inserted
while counter <= max_index:
print(words[counter] + "!")
counter = counter + 1
+ 1
what is your question?
0
Can this be a problem doing this shortcut?