Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JavaScript `for` loop to Python?

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.

like image 890
Tomas Avatar asked Dec 16 '22 06:12

Tomas


1 Answers

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.

like image 157
Tadeck Avatar answered Dec 27 '22 18:12

Tadeck