Home > database >  why integer cannot add with string
why integer cannot add with string

Time:12-10

n=int(input('Enter any number :'))
str1=""
for i in range(1,n 1):
  str1 =n
print(str1)

I tried the above mentioned code and it gave me typeerror and My expectation is e.g n=5 output : 12345

CodePudding user response:

There are two error in your code:

  1. You attempt to concatenate n instead of i.
  2. It is not possible to concatenate an integer to string value.

Now, this is my suggestion:

n=int(input('Enter any number :'))
str1=""
for i in range(1,n 1):
  str1 =str(i)
print(str1)

CodePudding user response:

your tried concatenate string and int thats why you get typeerror

 n=int(input('Enter any number :'))
    str1=[]
    for i in range(1,n 1):
      str1.append(i)
    print(*str1)

CodePudding user response:

As others mentioned, you have to cast your integer into string before concatenating, Use below, this method is called as 'list comprehension'

 n=int(input('Enter any number :'))
''.join([str(i) for i in range(1,n 1)])

CodePudding user response:

In Python, if you try to concatenate a string with an integer using the operator, you will get a runtime error. That's because Python is strongly typed language. There are various other ways to perform this operation. I found a lot of similar questions asked before on Stack Overflow. For example, this one might give you your answer.

  • Related