-1

Please help. I'm learning python and this challenge is driving me bananas as I can't get it right and don't know why. I suspect there is an issue with the step in the range but the book I'm learning from is no help. Please do not provide just the answer, please also tell me why/how? Thank you in advance.

The problem: If I have 2 values called num1 and num2 and num1 is always less than or equal to num2, then list all numbers between num1 and num2 in increments of 5 (as well as num 1 to start and num2 to end in that output).

Input: -15 10

Output I'm getting is: -15, 10, 5

Output should be: -15 -10 -5 0 5 10

currently using:

ig1 = int(input('Enter your first integer: '))
ig2 = int(input('Enter your second integer: '))

range_list = range(ig1, ig2, 5)

if ig1 <= ig2:
    print(range_list)
else:
    print("Second integer can't be less than the first.")
Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
  • 1
    when you use range, you are creating a "generator" that is a type of object that yield values one by one. So you will never have the whole array this way. A fast workaround is to call the range as a list using `list(range(ig1,ig2,5))`this way you will have the whole list.. Also if you want the last number (if step allows you) in the list you need to use `ig2+1` as stop for range – Ulises Bussi Nov 02 '21 at 22:21
  • 4
    @UlisesBussi: A `range` is actually a full-featured immutable sequence type, not just a one-time use iterator/generator. Most people only see it used as an iterable in a context where an iterator would be fine, but it's indexable, sliceable, has a length, etc. – ShadowRanger Nov 02 '21 at 22:26
  • @ShadowRanger thank's for the ampliation, I didn't know that! – Ulises Bussi Nov 02 '21 at 22:33

1 Answers1

6

A range (in Python 3) is a kind of object used to represent a sequence of numbers. It's not a list. If you create a range(-15,10,5) object and print it, you'll see

range(-15, 10, 5)

If you want a list, you can easily convert it to one:

range_list = list(range(ig1, ig2, 5))

If you print that you'll see

[-15, -10, -5, 0, 5]

which are the numbers contained in the range. If you want 10 (your ig2) to be included in the list, increase the second argument (the stop value) in the range so that it is after the number that you want to include:

range_list = list(range(ig1, ig2+1, 5))
khelwood
  • 55,782
  • 14
  • 81
  • 108