0

I was trying different ways of using the range() function in Python and when I tried this:

print(range(1, 20, 2), end=" ")

I got an output like this: range(1, 20, 2 ) , when I was expecting something like this: 1 3 5 7 9 11 13 15 17 19 Why is this the case?

Also, are there any other ways to print a range of numbers other than using a loop statement, or is it compulsory to always use loops if I want a sequence of numbers using range()?

Michael Wheeler
  • 849
  • 1
  • 10
  • 29

2 Answers2

2

range(1, 20, 2) return object, you need iterate over this and print all element you can do this with for-loop or print do this for you but you need pass list to print and print iterate over all element in list.

You can use * then get all elements and print what you want:

>>> print(*range(1, 20, 2), end = " ")
1 3 5 7 9 11 13 15 17 19 

# this same like below:

>>> list(range(1,20,2))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

>>> print(*[1, 3, 5, 7, 9, 11, 13, 15, 17, 19], sep= ' ')
1 3 5 7 9 11 13 15 17 19 
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
2

The reason you are getting the output range(1, 20, 2) is because you are trying to print an object of the class range, and as @user1740577 pointed out, you can use print(*range(1, 20, 2), end = " ") to print out the numbers as you intend to.

Karan Batavia
  • 189
  • 1
  • 11