Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
a question about for loop
words = ["hello", "world", "spam", "eggs"] for word in words: print(word + "!") a code like above, there is a result unexpectedlly. I mean I didn't even assign any value to "word", how come??
4 Answers
+ 4
please indent the print statement
+ 3
You can see a for loop as a sort of sequential assignment.
In effect it is the same as writing:
word = words[0]
print(word+'!')
word = words[1]
...
+ 3
word in this case is already recognized as starting at 0 so when it is initiated / ran it recognizes every word in the array of words
https://code.sololearn.com/caSPVH0wnd4z/?ref=app
+ 2
'word' is like an iterator which iterates over every element inside the list.
It is similar to enhanced for loop in Java.
Python-> for x in y:
Java-> for(int x : y)