4

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.

0

2 Answers 2

6

for loops in Python

It 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

Note

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.