r/learnpython • • Jul 31 '22

Loops in python are weird

I recently started learning python programming. I also had some exposure to programming in my high school.

Today I studied loops but I found them a little bit weird...they do not have any initialisation, condition and increment like other languages like javascript.

It is very confusing to me PLEASE HELP!!

0 Upvotes

7 comments sorted by

16

u/Green-Sympathy-4177 Jul 31 '22

they do not have any initialisation, condition and increment like other languages like javascript

Actually you can get the same result:

js:

for (var i = start; i < end; i += step ) {
    console.log(i)
}

python:

for i in range(start, end, step):
    print(i)

I would say that javascript is weird, why is it that to iterate over an array you have to do this in js:

var x = [1,2,3]

x.forEach( (xi) => {
    console.log(xi)
})

Python:

x = [1,2,3]

for xi in x:
    print(xi)

11

u/sisko6969 Jul 31 '22

I'm here to say the same. The weird ones are all other languages, python, in this, is the prettier one.

7

u/shiftybyte Jul 31 '22

Python's for loop are equivalent to javascript's foreach loops.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Python also has while loops for a more classical init/condition/increment approach.

8

u/skyboyer007 Jul 31 '22 edited Jul 31 '22

...or rather for .. of .. in JS

but with optional access to index(if using enumerate())

6

u/EddyBot Der-Eddy Jul 31 '22

When I started I felt the same but honestly nowadays the way Python does for loops (or other languages "foreach") is much more common to use that I don't feel that way anymore
it is so ridiculously simple and useful in Python and I wonder why it isn't more common across other programming languages

6

u/[deleted] Jul 31 '22

they do not have any initialisation, condition and increment like other languages like javascript.

Python (and many more modern languages that aren’t tied to 60-year-old C concepts) figure that the only reason you’re counting up an index variable from 0 was to access the elements of a collection anyway, so just… do that. Yield the elements of a collection in order.