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.
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() .
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.
Yes, it is possible to change the range from inside the loop, see the new answer below.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With