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?

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

The * performs unpacking, each element will be a parameter of print
@mozway thanks, I didn't know that before.
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")

1 Comment

(Mis)using a list comprehension just to invoke a side effect isn't the best of ideas. It confuses future readers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.