for loop in Python

Question:

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++.

Asked By: newprint

||

Answers:

Try using this:

for k in range(1,c+1,2):
Answered By: carlosdc

You should also know that in Python, iterating over integer indices is bad style, and also slower than the alternative. If you just want to look at each of the items in a list or dict, loop directly through the list or dict.

mylist = [1,2,3]
for item in mylist:
    print item

mydict  = {1:'one', 2:'two', 3:'three'}
for key in mydict:
    print key, mydict[key]

This is actually faster than using the above code with range(), and removes the extraneous i variable.

If you need to edit items of a list in-place, then you do need the index, but there’s still a better way:

for i, item in enumerate(mylist):
    mylist[i] = item**2

Again, this is both faster and considered more readable. This one of the main shifts in thinking you need to make when coming from C++ to Python.

Answered By: bukzor

If you want to write a loop in Python which prints some integer no etc, then just copy and paste this code, it’ll work a lot

# Display Value from 1 TO 3  
for i in range(1,4):
    print "",i,"value of loop"

# Loop for dictionary data type
  mydata = {"Fahim":"Pakistan", "Vedon":"China", "Bill":"USA"  }  
  for user, country in mydata.iteritems():
    print user, "belongs to " ,country
Answered By: Pir Fahim Shah

The answer is good, but for the people that want this with range(), the form to do is:

range(end):

>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start,end):

 >>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

range(start,end, step):

 >>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]

In Python you generally have for in loops instead of general for loops like C/C++, but you can achieve the same thing with the following code.

for k in range(1, c+1, 2):
  do something with k

Reference Loop in Python.

Answered By: Octane

In C/C++, we can do the following, as you mentioned

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

We know that here k starts with 1 and go till (predefined) c with step value 1 or 2 gradually. We can do this in Python by following,

for k in range(1,c+1):
for k in range(1,c+1,2):

Check this for more in depth.

Answered By: M.Innat

Use this instead of a for loop:

k = 1
while k <= c:
   #code
   k += 1
Answered By: lukaslanger

The range() function in python is a way to generate a sequence. Sequences are objects that can be indexed, like lists, strings, and tuples. An easy way to check for a sequence is to try retrieve indexed elements from them. It can also be checked using the Sequence Abstract Base Class(ABC) from the collections module.

from collections import Sequence as sq
isinstance(foo, sq)

The range() takes three arguments start, stop and step.

  1. start : The staring element of the required sequence
  2. stop : (n+1)th element of the required sequence
  3. step : The required gap between the elements of the sequence. It is an optional parameter that defaults to 1.

To get your desired result you can make use of the below syntax.

range(1,c+1,2)
Answered By: hyder47

Here are some example to iterate over integer range and string:

#(initial,final but not included,gap)
for i in range(1,10,2): 
  print(i); 
1,3,5,7,9

# (initial, final but not included)  
# note: 4 not included
for i in range (1,4): 
   print(i);
1,2,3 

#note: 5 not included
for i in range (5):
  print (i);
0,1,2,3,4 

# you can also iterate over strings
myList = ["ml","ai","dl"];  

for i in myList:
  print(i);
output:  ml,ai,dl
Answered By: RITTIK

Despite asking a FOR STATEMENT, just for the record as bonus, alternatively with WHILE, it’d be:

k=1
while k<c:
      #
      # your loop block here
      #
      k+=2
Answered By: PYK

You can use the below format.

for i in range(0, 10, 2):
    print(i,' ', end='')
print('')

and this will print;

0  2  4  6  8 
Answered By: Randil Tennakoon

Getting the power of a number using FOR LOOP

def power(x, y):

result = 1
for i in range(y):
    result = result * x
return result

print(power(2, 3))

Output is 8, why?

  • We created a function named power to store the commands that we want to deal with.

  • Since we set y equal to 3 after we invocate the function, we will be able to iterate the for loop 3 time from 0 index to 2nd index iteration not including 3rd index.

  • in the first iteration or the 0 index iteration, result is set equal to 1, meaning inside the for loop, result is equal to 1 * 2. 2 because that is the equivalent amount of x when we called that power function. Therefore, the result that will be returned in the first iteration is 2.

  • Second iteration of for loop or in the 1st index iteration, we know the result is equal to 2, therefore, result will be equal to 2 * 2. This time the result that will be returned will be equal to 4.

  • lastly, the 3rd iterelation or the 2nd index iteration sets the value of result equal to 4, so that, the result inside the for loop will be equal to 4 * 2. Keep in mind that 2 is the equivalent of our first parameter in our power function. With that, 4 * 2 is equal to 8, that is why the final returned result of this for loop is 8.

On the other hand, we can simply get the power of a number in python by just simple typing 2**3

Answered By: Misa Carlo
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.