Programmer
Programmer

Reputation: 97

How does this program in python work?

I am new to Python and I am stuck at the following code:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
    print numbers

When I run this program, it prints the numbers sequence 10 times. How does this happen? I still haven't assigned a value to the variable number, so how does it check whether the number is in the range? As far as I know, the variable number has a null value.

Upvotes: 2

Views: 176

Answers (3)

Theox
Theox

Reputation: 1363

What you have here is the most basic for loop.

In a more general way, let's say you have a list L, with elements L1, L2, L3, L4, L5.

In Python, that is:

L = [L1, L2, L3, L4, L5]

Now if you loop through your list L, like this:

for element in L:
    print element

The variable element (which you have never assigned before!) will automatically be assigned to the value of the first element of the list L, which is L1. Then, in my example, this value, L1, will be printed.

After that, there are still other elements in the list! So the program will change the value of the variable element, and set it to the value of the second element of the list L, L2. Then it will print the value of element (so, L2), or whatever you want to do with it.

Upvotes: 4

Neaţu Ovidiu Gabriel
Neaţu Ovidiu Gabriel

Reputation: 903

Your print numbers instead of number.

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 122152

When you define a for loop:

for x in y:

this automatically assigns each value from the iterable y, in turn, to the variable name x.

You could add print number to your code to see what is happening on each iteration of the loop.

Upvotes: 3

Related Questions