How would you implement a for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How would you implement a for loop

How does it work

6th Jun 2017, 11:02 PM
Talia Pacelli
Talia Pacelli - avatar
2 Answers
+ 5
The for loop is another while loop essentially. You'd traditionally use it for a definite number of actions, eg calling a function (though this can be achieved through recursion, it's much simpler to read and Py focuses on readability). Say you wanted to do something a specific number of times and access an array(list) element, for is a very simple way to iterate through a list.
7th Jun 2017, 12:26 AM
Jamie
Jamie - avatar
+ 3
for loops are VERY useful once you understand them. for i in range(5): print(i) output: 0 1 2 3 4 What's happening is for ............ Declare the start of a for loop i ................ This is just a variable name. Like variables, it can be named anything. i is typical. in range() . Just one of many ways to choose the number of times to run the loop. Unlike a while loop that runs indefinitely, for loops generally run a set amount of times. myList=["A","B","C"] for i in myList: print(i) output: A B C Another typical use of for loops is to iterate thru a list. Like above. for i in range(5): print("*"*i) output: * ** *** **** They are fun
7th Jun 2017, 1:18 AM
LordHill
LordHill - avatar