Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a C-style for loop in Python?

Tags:

python

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.

like image 914
apscience Avatar asked Feb 26 '12 04:02

apscience


People also ask

Can you do C style for loops in Python?

for in Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages.

What is C style for loops?

The bash C-style for loop share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3).

What is loop in C in Python?

For loop in python is used to iterate over either a list, a tuple, a dictionary, a set, or a string. It allows us to efficiently write a loop that needs to execute a specific number of times. For loop is initialized using for keyword. For loop in C is a entry-cotrolled loop.


1 Answers

In C:

for(int i=0; i<9; i+=2) {     dosomething(i); } 

In python3:

for i in range(0, 9, 2):     dosomething(i) 

You just express the same idea in different languages.

like image 82
kev Avatar answered Oct 01 '22 20:10

kev