0

So I've been trying to figure how out how to print an ordered list of numbers that occur before a number, starting from one in python. Let me show you what I mean.

Here is my example.

x = 20
#I want to print this
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
#Another example
y = 5
1, 2, 3, 4, 5

Is there any piece of code or built-in function in python that will allow me to do this?

4 Answers4

4

If you simply want to print the numbers, you can unpack your range() object and use the sep keyword argument to add the commas:

>>> x = 20
>>> print(*range(1, x + 1), sep=', ')
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
>>>

For Python 2.x:

>>> from __future__ import print_function
>>> 
>>> x = 20
>>> print(*range(1, x + 1), sep=', ')
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
>>> 

This answer was inspired by @Grimmy's comment.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
2

You are looking for the range class. Normally a range initializes from a start value to the number before the stop value, so you need to add one to the end:

x = 20
print(list(range(1, x + 1)))

Using a range object has the advantage of storing all the information about the elements in a way that only requires the integers worth of storage. You can iterate over it and test for containment without spelling out all the list elements.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

A simple for loop

x = 20
for num in range(x):
    print(num, ", ", end=' ')

Though you'd have to do a fence-post trick with the comma, so Mad Physicist's response is good.

Mauricio
  • 419
  • 4
  • 14
  • 3
    It should be `range(1, x + 1)`. Also, `print(num, end=", ")` would work better. However, you are going to end up with a trailing `,`, which seems a bit odd. – idjaw Jul 16 '17 at 02:41
  • Easy to read and understand for newbies as well. – Grimmy Jul 16 '17 at 02:45
-1

You can try this:

x=20                    #The number you want
y=0                     #Counter vaiable
while True:             #Infinate loop
  print (y)             #Prints y
  y+=1                  #Adding 1 to y
  if y == x:          
    print (x)           #If y is the same as x,then print the last number
    break               #Stops the program

Does the same stuff but might be easier to understand.

Harshy
  • 13
  • 3