Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop in Python

Tags:

python

In C/C++, I can have the following loop

for(int k = 1; k <= c ; k +=2) 

How do the same thing in Python?

I can do this

for k in range(1,c): 

In Python, which would be identical to

for(int k = 1; k <= c ; k++) 

in C/C++.

like image 902
newprint Avatar asked Nov 13 '10 02:11

newprint


People also ask

What is a for loop in Python?

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

What is for loop in Python explain with example?

In the context of most data science work, Python for loops are used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. For example, a for loop would allow us to iterate through a list, performing the same action on each item in the list.

How do you write for loop in Python?

Let's go over the syntax of the for loop: It starts with the for keyword, followed by a value name that we assign to the item of the sequence ( country in this case). Then, the in keyword is followed by the name of the sequence that we want to iterate. The initializer section ends with “ : ”.

What are the 3 types of loops?

In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true. This particular condition is generally known as loop control.


1 Answers

Try using this:

for k in range(1,c+1,2): 
like image 188
carlosdc Avatar answered Oct 05 '22 22:10

carlosdc