How counter in for loop works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How counter in for loop works?

The Sololearn give us that example: words = ["hello", "world", "spam", "eggs"] for word in words: print(word + "!") But how we can use the variable which wasn't defined (wasn't declared)? And why we can't use case like " for word-1 in words"?

17th May 2017, 10:51 AM
HolyDiver
HolyDiver - avatar
2 Answers
+ 4
I know it can be weird, but the for loop in Python is not like the for loop in (nearly) all other languages. In Python, the for loop iterates over the collection you give it (in your example, words), element by element and stores each element in the variable you give it (in your example, word). The mechanism is different for C/C++/Java/whatever(ish) where the for loop looks like: for (initialisation ; exit condition ; end loop thing to repeat) Thus, usually iterates over INTEGERS. Well, I say Java... There is also a construct in Java to use the for loop like in Python
17th May 2017, 3:06 PM
Amaras A
Amaras A - avatar
+ 1
for loops are not that much of counters but more like "selectors" The example you gave selects one by one the elements contained in the array and operates with them once
17th May 2017, 11:00 AM
spcan
spcan - avatar