Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python for statement
by RS  admin@robinsnyder.com : 1024 x 640


1. Python for statement
In Python, the for loop is not like a for loop in C, Java, etc. The Python for is more like a for each iterator loop in some other languages.

2. End to begin of list
Here is a C-like way to process/print out elements of a list from end to beginning.

Here is the Python code [#1]

Here is the output of the Python code.

Here is a more Pythonic way to process/print out elements of a list from end to beginning.

Here is the Python code [#2]

Here is the output of the Python code.


3. Example
Try writing a short Python program to search through a list looking for an element and determine whether that element is in the list and do something only if that element is found. For now, do not use any Python iterators. Use a while loop. Do not use any functions, is this code example is being used for a specific point. Here is the Python code [#3]

Here is the output of the Python code.

Here is the Python code [#4]

Here is the output of the Python code.



Here is the associated code fragment whileloopgoto using goto statements for code fragment whileloop.


4. While else construct
Notice how the generated code can be modified slightly to support the else (i.e., nobreak) construct of the while or for.
L10: if ( ! (Condition) ) goto L20; Statements if (Break) go to L30; goto L10; L20: // no break // loop completed normally L30:


5. If then else goto conversion


Here is the generated code. Compare the else of the while.
L10: if ( ! (Condition) ) goto L20; Statements-Then-Part goto L30; L20: Statements-Else-Part L30:


6. History
During the "goto" wars (started by Edgar Dijkstra), Donald Knuth studied the usage of goto statements in programmer code. From this (as in the above example), he recommended the addition of an else to the while and for since the patterns matched very closely.

Today, the else to the while or for might be better thought of as the nobreak part of the while or for.


7. End of page

by RS  admin@robinsnyder.com : 1024 x 640