+ 1
Working of this loop??
Can somebody explain to me how this loop works? words = ["hello", "world", "spam", "eggs"] for word in words: print(word + "!")
6 ответов
+ 3
word is a temporal variable that will be only accessible during the for loop, and it will change its value for every time it loops.
words is the list where the for loop will "iterate" (loop). For every cicle the for loop iterates, it will change its value to the next element of a list until it reaches the last one.
So:
For every item on the list "words"
Print the value the variable "word" will take + !
+ 5
DEVANSH BANSAL
You have a list that contains items (in this case, string/words).
This part:
__________________
for word in words:
__________________
goes through each word in your list.
__________________
print(word+ “!“)
__________________
This parts adds this sign -> ! <- after every word. The plus means they are not seperate, but rather joined.
The output would therefore be:
_______________
hello!
world!
spam!
eggs!
________________
Hope this helps ☺️
+ 2
the program will look for every element of your list (words) then in the loop it will print them all .
(word) is the name of the elements, like( words[0] then, words[1]) and so.
At the end of your loop all of them will be printed
+ 1
Yes, "word" is like the conventional "i" in the for loop of other languages.
for loops in python have other useful functions too:
range(n) will iterate n times, starting with value zero and ending with n-1; if you want it to start with a value other than zero change it to range(1, n). Example: for i in range(100) will iterate with a value from 0 to 99
enumerate(iterable_object) will create a tupple for every item of the iterable object, that will contain the index of the item in the list and the item.
Example: for i in enumerate(["moon", "sun"]):
the first value of i would be (0, "moon") and the second (1, "sun")
You can also make it start with a value other than zero, I think it was like: for i in enumerate(iterable, start=1):
zip() will allow you to handle more than one variable in a single for loop, it can do other things too but that's what I use it for. Example:
for i, j in zip(range(100), range(900, 1001)):
0
So if i put anything other than word then too it will work?
0
Thanks