0
Question is about for loops and range
In for loops if we give command For i in range(1,-10,2) and print i These shows no output .why
4 ответов
0
This is because you are using a descending loop. The first number in the range should be less than the second number. But you have 1 greater than -10.2. To display the numbers in descending order, use slices.
+ 2
Poorvik AS
In addition to Mila suggestion, you can also use negative step value to run the loop in reverse order.
For example:
for i in range(1, -10, -1):
print(i)
0
To better understand range() function in python, you can print the help with "print(help(range))
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return an object that produces a sequence of integers from start (inclusive)
| to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
| start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
| These are exactly the valid indices for a list of 4 elements.
| When step is given, it specifies the increment (or decrement).
range(stop) -> range object
The basic usage, repeat "stop" times. So range(10) means repeat 10 times.
range(start, stop[, step]) -> range object
In this usage, you can use 2 or 3 argument, the last [step] argument is optional.
A. range(2, 10) gives you 2, 3, 4, ... 9
B. range(2, 10, 3) gives you 2, 5, 8
And step can be a negative number, which lets you print from positive to negative.
range(1, -10, -2) gives you 1, -1, -3, ... -9