Home > Software engineering >  Negative numbers in range() function - how to print from positive to negative numbers?
Negative numbers in range() function - how to print from positive to negative numbers?

Time:11-05

I'm trying to create a function that prints a board with labelled axes. This is my code for printing the y axis.

y = [-1, 4]

y_axis = range(y[0], y[1] 1)

for i in y_axis: # rows 
    print(y_axis[i]) 

This is the output that I get:

4
-1
0
1
2
3

Why does it not start from y[0] and go in integer increments until y[1] 1 ? I thought that was the output of the range() function. For my project, I need this piece of code to output the following instead:

4
3
2
1
0
-1

I don't understand how to get my desired result, I've been trying for hours! Any help is much appreciated, thanks

Edit: the tricky part is that this should be able to print in the correct order any kind of range: if I use a negative step it might not work correctly for all positive values etc A method like this doesn't work: -1 -> 4: range(y[0], y[1] 1) 4 -> -1: range(y[1], y[0]-1, -1)

I need a universal solution. could it have to do with the enumerate() function?

CodePudding user response:

Here's what you're looking for:

y = [-1, 4]

y_axis = range(y[1], y[0]-1, -1)

for i in y_axis:
    print(i)

There are two problems with your original code:

  1. Print should be the element, not indexing the list.

  2. Your range should start from 4 (first element) and end at -2 (second element). In order yo make sure you decrement, use the third argument of function range: step. step=-1 decrements from the first element to the last element. You can test the order of the items range outputs by doing:

    print([i for i in range(4, -2, -1)])

Hope this helped! Cheers! :)

  • Related