+ 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
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.")
+ 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.