Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how does a for loop with `range` work?

Tags:

python

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 am more used to C++ & Java where I'd write the code like:

for (i = 1; i < 101; i++) {    System.out.println(i);    i++; } 

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

like image 582
TopChef Avatar asked Jul 13 '10 23:07

TopChef


People also ask

How does a for loop work with range?

for loops repeat a block of code for all of the values in a list, array, string, or range() . We can use a range() to simplify writing a for loop. The stop value of the range() must be specified, but we can also modify the start ing value and the step between integers in the range() .

Is Python for loop range inclusive?

Python range is inclusive because it starts with the first argument of the range() method, but it does not end with the second argument of the range() method; it ends with the end – 1 index.

Can you change the range of a for loop in Python?

Yes, it is possible to change the range from inside the loop, see the new answer below.


1 Answers

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); } 
like image 166
João Silva Avatar answered Oct 13 '22 11:10

João Silva