Using For in Python

3

In Python it is only possible to work with 'for' (loop ) using a list?

Is not it possible only with an integer like in other languages?

    
asked by anonymous 15.11.2016 / 03:17

2 answers

4

Yes, using a data strip is the idiomatic way of doing it in Python and does not have the for you know in other languages. What you can do is use while , is almost equal to for traditional.

x = 0
while x < 3:
    print(x)
    x += 1

Idiomatic form:

for x in range(0, 3):
    print(x)

See running on ideone .

Python has else for for which is useful and rare in other languages.

    
15.11.2016 / 03:23
-1

Complementing the answer, note that you can use range or xragne in the idiomatic form reported in the previous answer.

Using the range pre-allocates all items to be iterated in memory, which can be a problem if the numbers are too large. In these cases it is more recommended to use xrange, which acts as a generator, allocating objects on demand.

    
18.11.2016 / 03:37