Saahil Shaikh
Saahil Shaikh

Reputation: 25

How do I print numbers from 1 to n in python in a single line without spaces?

print(*range(1, int(input())+1), sep='') 

This was the code I found in a discussion on hacker rank. But I did not understand it. Can anyone please explain this?

Upvotes: 0

Views: 3163

Answers (2)

Przemosz
Przemosz

Reputation: 111

Ok so we have print function. Inside we have this strange *range(1, int(input())+1) this is range function which return value from 1 to n (n is typed in input) in a form of a range object. * unpack this object to form like: 1 2 3 4 ... with spaces, so we have this sep='', keyword argument that makes separation from space to '' (no separate between).
Also you can do it like that:

n = input("Type integer value: ")
try:
    [print(x+1,end="") for x in range(int(n))]
except ValueError:
    exit("Typed string not number")

Upvotes: 1

Agent Biscutt
Agent Biscutt

Reputation: 737

So, from what I can tell, this is how it works:

int(input())

This takes input from the user. Next;

range(1,...+1)

This creates a range from 1 to our number we inputted earlier. The +1 means that it will include the max number. And then:

print(*...,sep='')

The * sign, from what I can tell, just effectively returns each value in our range one to be printed. The sep='' just means each value is separated by '' or nothing.

Hope this is useful to you.

[EDIT]

More on star and double star expressions in this post: What does the star and doublestar operator mean in a function call?

Upvotes: 1

Related Questions