Python Range between two numbers by steps of 5?

Question:

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.")
Asked By: Cox QC

||

Answers:

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))
Answered By: khelwood

I would suggest you to use loop function.

first = int(input())
second = int(input())

if first <= second: 
    for i in range(first, second + 1, 5):  #here the loop body starts, the range of numbers and the gap between the numbers are defined. 
        print(i, end = ' ')                #here it is to print out the numbers in your range, and therefore generate a list you asked for. 
    print()
else:
    print("Second integer can't be less than the first.")
Answered By: Royal Yu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.