Variables in a loop, Newby question

Tobias M. tm at tobix.eu
Tue Dec 24 11:24:01 EST 2013


On 24.12.2013 17:07, 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 could do:

x = 1
while x < 10:
     print(x)
     x += 1

But that would be very "unpythonic".
Instead I would use a for loop and the range() function:

for x in range(1,10):
     print(x)

This is really short and readable.

I recommend reading the python tutorial to understand the basics:
http://docs.python.org/3/tutorial/





More information about the Python-list mailing list