0
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?

Agent Biscutt
  • 712
  • 4
  • 17
Saahil Shaikh
  • 25
  • 1
  • 4

2 Answers2

1

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?

Agent Biscutt
  • 712
  • 4
  • 17
1

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")
Przemosz
  • 101
  • 5
  • 1
    (Mis)using a list comprehension just to invoke a side effect isn't the best of ideas. It confuses future readers. – Matthias Nov 04 '21 at 07:33