For Loops | SoloLearn: Learn to code for FREE!


For Loops

Could anyone explain to me how does computer know the variable 'word' here? Like, we can put here anything? And still, how does it know what word is? It's never defined before so I have no idea why! words = ["hello", "world", "spam", "eggs"] for word in words: print(word + "!")

4/12/2018 1:51:23 PM


5 Answers

New Answer


so the thing is: the for loop will iterate (loop through) the whole array 'words'. for every word that you have stored in 'words' it will load it to the variable 'word' and print it, as you specified. so, here we go: for <- you tell the interpreter that it is a loop word <- WHEREto store variables (from an array or other thing, specified as fours term (wait)) in <- tells from which array you take items words <- name of that array for <name of variable> in <array name> for loop will do the specified thing ( print in your example) with EVERY thing that is stored in the array ('words' in your example)


it gets auto-defined, it is supposed to iterate through words, thus, there are secret assignments on the background (word = words[0] then : word = words[1]....)


This is a for loop and you can replace word by any word you want as like: for n in words: print(n+"!") word here is used in arbitrary choice of terms and the entire meaning of the for loop is: for element in words print this element with exclamation mark"!"


definition of for loop?


deoends of the loop tho. in c++ for loop is defined slightly different that the one here, fut lets focus on the given example. For loop will iterate through every item in an array and you can do some things to each of them. that is for loop, nothing very special