+ 1

Will anyone explain me the prototype and working of a for loop in python ?

4th Jun 2017, 3:03 PM
Suraj Vishwakarma
Suraj Vishwakarma - avatar
3 Respostas
+ 8
Don't really understand the prototype part of the question, but as far as a for loop is concerned: A 'for' loop when run, iterates a variable through an interator (usually a collection, object, range, list, set, etc.) In each iteration the code within the loop is executed and the iterated variable assumes consecutive values of the iterator. Let's consider an example: b = [1, 2, '5', null] for a in b: print(a) This loop makes a equal to 1 and print it, then it makes a equal to 2, prints it, then makes a equal to '5', prints it and finally it nulls a and prints it. Unless you specify it somehow in the loop, it will continue to iterate until the end of the iterator is reached. So you can be sure that it will run as many times as the size of the iterator is.
4th Jun 2017, 3:29 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
In addition to @Kuba Siekierzyński answer, in Python the range() function is useful and used a lot to make range loop, as it don't provide the classical 'prototype' way of most languages: for (var i=0; i<10; i++) { /* some code to repeat 10 times */ } ... can be write in Python: for i in range(10): # some code to repeat 10 times Concretely, range() function return a generated list object through wich you can iterate withe the 'for' statement... Check Python references to learn how many and how works possible parameters ( upon 3, defining boundaries and step ^^ )
4th Jun 2017, 5:21 PM
visph
visph - avatar
+ 1
for loop is used if you want to run a script more than once
5th Jun 2017, 2:47 AM
Akash Vijayan
Akash Vijayan - avatar