a question about for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

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??

21st Feb 2020, 7:32 PM
Jon LIU
Jon LIU - avatar
4 Answers
+ 4
please indent the print statement
21st Feb 2020, 7:50 PM
Oma Falk
Oma Falk - avatar
+ 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] ...
21st Feb 2020, 7:50 PM
HonFu
HonFu - avatar
+ 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
21st Feb 2020, 8:07 PM
BroFar
BroFar - avatar
+ 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)
21st Feb 2020, 7:52 PM
Avinesh
Avinesh - avatar