Print function input into int

Question:

My goal is very simple, which makes it all the more irritating that I’m repeatedly failing:

I wish to turn an input integer into a string made up of all numbers within the input range, so if the input is 3, the code would be:
print(*range(1, 3+1), sep="")

which obviously works, however when using an n = input() , no matter where I put the str(), I get the same error:

"Can't convert 'int' object to str implicitly"

I feel sorry to waste your collective time on such an annoyingly trivial task..

My code:

n= input()
print(*range(1, n+1), sep="")

I’ve also tried list comprehensions (my ultimate goal is to have this all on one line):

[print(*range(1,n+1),sep="") | n = input() ]

I know this is not proper syntax, how on earth am I supposed to word this properly?

This didn’t help, ditto this, ditto this, I give up –> ask S.O.

Asked By: David Andrei Ned

||

Answers:

I see no reason why you would use str here, you should use int; the value returned from input is of type str and you need to transform it.

A one-liner could look like this:

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

Where input is wrapped in int to transform the str returned to an int and supply it as an argument to range.

As an addendum, your error here is caused by n + 1 in your range call where n is still an str; Python won’t implicitly transform the value held by n to an int and perform the operation; it’ll complain:

n = '1'
n + 1 
TypeErrorTraceback (most recent call last)
<ipython-input-117-a5b1a168a772> in <module>()
----> 1 n + 1

TypeError: Can't convert 'int' object to str implicitly

That’s why you need to be explicit and wrap it in int(). Additionally, take note that the one liner will fail with input that can’t be transformed to an int, you need to wrap it in a try-except statement to handle that if needed.

In your code, you should just be able to do:

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

But you would also want to have some error checking to ensure that a number is actually entered into the prompt.

A one-liner that works:

print(*range(1, int(input()) + 1), sep="")
Answered By: ode2k
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.