Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie has questions about the FOR statement:

Status
Not open for further replies.

Coffeecrab

Programmer
Jan 19, 2000
2
0
0
US
I am new to python, although I know intermediate C++ and a little JavaScript. In Python, I have trouble understanding Guido's implementation of the FOR loop. Could some please explain what 'for _ in _' means? I wish he'd've taken the for(i = 2; i < 10; i++) which as of now I think is more powerful. (Especially since I can't even use for loops in python) :)
 
I'm fairly new to Python myself but this example might help, it's from the tutorial . . . <br>
<br>
&gt;&gt;&gt; # Measure some strings:<br>
... a = ['cat', 'window', 'defenestrate']<br>
&gt;&gt;&gt; for x in a:<br>
... print x, len(x)<br>
... <br>
cat 3<br>
window 6<br>
defenestrate 12<br>
<br>
'a' is a list, in this case, it's a list of strings. What the &quot;for _in_ &quot; says is, 'for every item in &quot;a,&quot; print the item and the length of the string.' This allows for greater flexibilty but can cause some confusion for those of us who are use to iteration via integers.<br>
<br>
You can change the list of strings to a list of numbers but the 'for loop' will loop for the _number_of_items_ in the list.<br>

 
Well if you want the same as for(;;)<br>then just simulate it:<br><br>&nbsp;&nbsp;&nbsp;&nbsp;i=2<br>&nbsp;&nbsp;&nbsp;&nbsp;while i&lt;10:<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# body<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;i=i+1<br><br>otherwise if its just the simple iterator<br>you want...<br>&nbsp;&nbsp;&nbsp;&nbsp;for i in range(2,10):<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# body<br><br>is your iterator (range() creates a list like 2ffat mentioned)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top