tags:

views:

115

answers:

5
for number in range(1,101): 
print number

Can someone please explain to me why the above code prints 1-100? I understand that the range function excludes the last number in the specified range, however, what is the 'number' part of the syntax?

I more used to C++ & Java where i'd write the code like:

for (i = 1; i<101; i++)
  {return i;
   i++;
  }

So what exactly is 'number'? I'm sure i'm looking too far into this and there is a simple question.

+6  A: 

number is equivalent to i in your C loop, i.e., it is a variable that holds the value of each loop iteration.

A simple translation of your Python code to C would result in something along these lines:

for (int number = 1; number < 101; number++) {
  printf("%d\n", number);
}
JG
Thanks man. That makes it easier. What is the incrementation process?
range() returns a sequence (an abstraction that behaves like a list of numbers), and 'for number in...' is said to 'iterate over the sequence'. There's no exact analog to the sequence in the C version, but the relationship between the elements of the range sequence is where the 'incrementation' happens.
Russell Borogove
+2  A: 

Python 2.7 documentation states:

range([start], stop[, step])¶

This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised)

EDIT: You may also want to look at xrange. EDIT: So basically:

for ( start ; stop ; step )
range( start, stop, step ) // where start and step are optional
nevets1219
A: 

number is a variable in which each value in the range is placed.

range actually returns an iterator, and the for is responsible for advancing it through the range.

zdan
A: 

range is the list of the numbers 1 to 100.

number then references each object in that list

sre
+1  A: 

As JG said, number is your variable (much like i in your C code). A for loop in python is really like a foreach loop in C# (I think Visual C++ has it too). Basically, it iterates over a container. So you can use that syntax with lists too:

fib = [0,1,1,2,3,5,8]
for number in fib:
    print number

A range object acts sort of like a container, containing all the numbers between a and b.

Smashery