Python's for loops are different. i gets reassigned to the next value every time through the loop.
The following will do what you want, because it is taking the literal version of what C++ is doing:
i = 0
while i < some_value:
if cond...:
i+=1
...code...
i+=1
Here's why:
in C++, the following code segments are equivalent:
for(..a..; ..b..; ..c..) {
...code...
}
and
..a..
while(..b..) {
..code..
..c..
}
whereas the python for loop looks something like:
for x in ..a..:
..code..
turns into
my_iter = iter(..a..)
while (my_iter is not empty):
x = my_iter.next()
..code..
Answer from jakebman on Stack Overflow"for i in range()" to do an infinite loop with a counter - Ideas - Discussions on Python.org
A single python loop from zero to n to zero - Stack Overflow
How do you start a for loop at 1 instead of 0?
What does "for i in range" mean in Python?
Videos
Python's for loops are different. i gets reassigned to the next value every time through the loop.
The following will do what you want, because it is taking the literal version of what C++ is doing:
i = 0
while i < some_value:
if cond...:
i+=1
...code...
i+=1
Here's why:
in C++, the following code segments are equivalent:
for(..a..; ..b..; ..c..) {
...code...
}
and
..a..
while(..b..) {
..code..
..c..
}
whereas the python for loop looks something like:
for x in ..a..:
..code..
turns into
my_iter = iter(..a..)
while (my_iter is not empty):
x = my_iter.next()
..code..
There is a continue keyword which skips the current iteration and advances to the next one (and a break keyword which skips all loop iterations and exits the loop):
for i in range(10):
if i % 2 == 0:
# skip even numbers
continue
print i
You can use itertools for that:
If you want to go to 1024 and back once, you can use:
from itertools import chain
for i in chain(range(0,1024),range(1024,0,-1)):
print(i)
In case you will need this quite often, you can use a function to generate the iterable:
def range_back(start,end):
return chain(range(start,end),range(end,start,-1))
and use it like:
for i in range_back(0,1024):
print(i)
Or if you want to do this an infinite amount of times:
from itertools import chain, cycle
for i in cycle(chain(range(0,1024),range(1024,0,-1))):
print(i) chain two iterables:
import itertools
for i in itertools.chain(range(1+n), reversed(range(n))):
do_whatever(i)
I am pulling data from a dictionary and appending it to a list, but it appears that dictionary keys start at 1, not 0.
We have been taught to use for loops for this kind of task, but they initialize at 0. Can I start at 1? If not, what is an alternative? Thanks!
for i in range(len(dict)):
<code goes here>