I want to use the traditional C-style for loop in Python. I want to loop through characters of a string, but also know what it is, and be able to jump through characters (e.g. i =5 somewhere in the code).
for with range doesn’t give me the flexibility of an actual for loop.
There is no simple, precise equivalent of C’s
forstatement in Python. Other answers cover using a Pythonforstatement with a range, and that is absolutely what you should do when possible.If you want to be able to modify the loop variable in the loop (and have it affect subsequent iterations), you have to use a
whileloop:But in that loop, a
continuestatement will not have the same effect that acontinuestatement would have in a Cforloop. If you wantcontinueto work the way it does in C, you have to throw in atry/finallystatement:As you can see, this is pretty ugly. You should look for a more Pythonic way to write your loop.
UPDATE
This just occurred to me… there is a complicated answer that lets you use a normal Python
forloop like a C-style loop, and allows updating the loop variable, by writing a custom iterator. I wouldn’t recommend this solution for any real programs, but it’s a fun exercise.Example “C-style” for loop:
Output:
The trick is
forrangeuses a subclass ofintthat adds anupdatemethod. Implementation offorrange: