+ 1

A python question from a beginner

character_name = input("Your name: ") birth_year = input("Your bith year: ") current_year = 2022 age = int(current_year) - int(birth_year) print(character_name + ", you are" + age + "years old.") Question is: why it doesn't work and how to do it right

11th Nov 2022, 6:49 AM
Serdar Annaorazov
Serdar Annaorazov - avatar
2 Respuestas
+ 5
The 'age' in the print statement is an integer. You have to first convert it to a string in order to use string concatenation (+), which is different from the addition operator (also +). The difference being the type of operands used: str + str (string concat) int + str (syntax error) int + int (addition) Try this: print(character_name + ", you are" + str(age) + "years old.")
11th Nov 2022, 6:58 AM
Mozzy
Mozzy - avatar
+ 4
As an addition to Serdars solution: For problems like this Stringtemplates do it: print(f"{character_name} you are {age} years old.") the f before the Strings starts the miracle of curly brackets which are replaced by the expression inside. It is modern and confortable.
11th Nov 2022, 9:24 AM
Oma Falk
Oma Falk - avatar