Reputation: 47
I am new to Python and want convert this small JavaScript code to Python. How can I do that?
for (var y = 0; y < 128; y += 1024) {
for (var x = 0; x < 64; x += 1024) {
// skipped
}
}
I searched a lot in Google, but found nothing.
Upvotes: 4
Views: 3213
Reputation: 137360
for
loops in PythonIt can be easily converted using range()
or xrange()
function. The xrange()
is an iterator version, which means it is more efficient (range()
would first create a list you would be iterating through). Its syntax is the following: xrange([start], stop[, step])
. See the following:
for y in xrange(0, 128, 1024):
for x in xrange(0, 64, 1024):
# here you have x and y
But I hope you have noticed, that due to the fact, that you are incrementing y
and x
with each respective loop by 1024, you will actually receive something similar to this:
var y = 0;
var x = 0;
or, in Python:
x = 0
y = 0
Anyway, it is just additional note about the code you have given as example.
Upvotes: 6
Reputation: 816462
Your code will only perform one iteration in each loop, so you don't even need a loop:
y = 0
x = 0
# do whatever with x and y here
In general, you can use range([start], stop[, step])
[docs] to simulate such a for
loop.
For example:
for(var i = 0; i < 10; i += 2)
becomes
for i in range(0, 10, 2)
Upvotes: 6