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

For loop

I can't understand what a for loop is, especially when it comes to " for i in ...." I could not understand the i function in it, that is what confuses me about the for loop. Can somebody please tell me what a for loop is? Thank you

24th May 2022, 10:57 PM
Danish Zubair
Danish Zubair - avatar
3 Answers
+ 7
A loop has a head and a body. In the head you set the condition for the loop, and for every loop, the code in the body will be executed: for i in [3, 5, 9]: print(i) In the for loop above, i is a variable that assign the value in the list [3, 5, 9], one value at every loop. There are three values in the list, so at the first loop i = 3, next loop i = 5 and in the last loop i = 9 In every loop the code in body vill be executed: print(i). So the loop above vill be the same as write the code: print(3) print(5) print(9)
24th May 2022, 11:46 PM
Per Bratthammar
Per Bratthammar - avatar
+ 2
If it helps, read it like, ā€œFor every item in the iterableā€¦ā€ That iterable can be a list, tuple, set, etc. or could also be a range object. It will run through each item in the iterable and do/calculate something
25th May 2022, 10:45 PM
Andrew Johnson
Andrew Johnson - avatar
+ 1
Thank you soo much, it is really clear now.
25th May 2022, 6:42 AM
Danish Zubair
Danish Zubair - avatar