Python Forum

Full Version: can only concatenate str (not "int") to str
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
what do I do to get a int and a str to concatenate?
I am playing with the idle but I can't seem to make this work.
################################################################################

name = input('enter your name: ')
age = int(input('enter your age: ')) 



while ( name != " " ):
    print('hello ' + name + ' you are ' + age + " years old")
    if (age < 18):
        print('go home kid')
    elif (age > 100):
        print('really hanging in there huh')
    break
################################################################################


I also tried age=input('enter your name') to no avail.


print('hello' + name + 'you are ' + int(age) + ' years old' didn't get it either.


I'm just messing around and wondering why is it that I am having a hard time trying to print
hello str you are int years old? with the conditions in the code also.
Please use proper code tags while posting a thread.
The problem is python can't just join a string and an integer together, because they are two different things and hence Python has no clue - should it add them like an integer or join them like a string ?? Confused
So there are 2 ways to defeat this -
  1. First, you can change the integer into a string, like
    print('hello ' + name + ' you are ' + str(age) + " years old")
    OR

  2. You can use commas -
    print('hello ' , name , ' you are ' , age , " years old")
Python doesn't know how to add a word and a number, so it says "cannot concatenate 'str' and 'int' objects." A word that you put in quotes is just a string of letters called a str in python. Numbers that don't have a decimal point are integers and are called int in python.
Or you can use f string format
age = 20
print(f'Hello, I am {age} years old.')
(May-27-2020, 11:04 AM)menator01 Wrote: [ -> ]Or you can use f string format
age = 20
print(f'Hello, I am {age} years old.')

I had totally forgotten about f-strings Think
(May-27-2020, 11:27 AM)pyzyx3qwerty Wrote: [ -> ]
(May-27-2020, 11:04 AM)menator01 Wrote: [ -> ]Or you can use f string format
age = 20
print(f'Hello, I am {age} years old.')

I had totally forgotten about f-strings Think

Or:

age = 20
print('I am {} years old.'.format(age))
thanks for the replies, the thing is I didnt realize that I was adding.
so the commas was the way to go for this instance, thanks again.
btw I am not 100 percent sure what is meant by placing tags but I will look into that.
(May-28-2020, 06:34 AM)gr3yali3n Wrote: [ -> ]thanks for the replies, the thing is I didnt realize that I was adding.
so the commas was the way to go for this instance, thanks again.
btw I am not 100 percent sure what is meant by placing tags but I will look into that.

Look at the note left by the moderator in your thread - it's marked in red