Variables in a loop, Newby question
Peter Otten
__peter__ at web.de
Tue Dec 24 11:29:45 EST 2013
vanommen.robert at gmail.com wrote:
> Hello, for the first time I'm trying te create a little Python program.
> (on a raspberri Pi)
>
> I don't understand the handling of variables in a loop with Python.
>
>
> Lets say i want something like this.
>
> x = 1
> while x <> 10
> var x = x
> x = x + 1
>
> The results must be:
>
> var1 = 1
> var2 = 2
>
> enz. until var9 = 9
>
> How do i program this in python?
You are trying to generate a variable name programatically. While this is
possible in Python
>>> x = 1
>>> while x != 10:
... exec("var{} = x".format(x))
... x = x + 1
...
>>> var1
1
>>> var7
7
this is a really bad idea that you probably picked up from old code in a
lesser language. Don't do it that way!
In Python you should use a dict or a list, for example:
>>> var = [] # an empty list
>>> x = 0
>>> while x < 10:
... var.append(x) # append an item to the list
... x += 1
...
>>> var
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
This can be simplified to a single line:
>>> var = list(range(10))
A few usage examples:
>>> var[0]
0
>>> var[9]
9
>>> var[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
As you can see list indices are zero-based. A list of length 10 has items 0
to 9.
>>> var[7] += 42
>>> var
[0, 1, 2, 3, 4, 5, 6, 49, 8, 9]
>>> sum(var)
87
More information about the Python-list
mailing list