Python Forum

Full Version: What have I done wrong?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
So I am new to learning Phyton and I don't know what I did wrong here, I would appreciate it if you could help me and also if you could simplify your explanation a bit.

This is the code:

birthyear = input(' in what year were you born? ')
age = 2019 - int(birthyear)
print(' you are ' + age + ' years old. ')
And this is the error I get:

Error:
Traceback (most recent call last): File "C:/Users/alicf/PycharmProjects/NOOB/yildan yas hesabi/erdo.py", line 3, in <module> print(' you are ' + age + ' years old. ') TypeError: can only concatenate str (not "int") to str
The problem is that the + operator can't be used between a string (' you are ') and an int, such as age. So you need to either convert the int to a string before using the plus operator, like this:
print(' you are ' + str(age) + ' years old. ')
or better yet, use string formatting
print(' you are {} years old. '.format(age))
or if you're using the latest version of Python, you can even do this
print(f' you are {age} years old. ')
Thanks for your help, and what does the f stand for on your last example?
(Sep-23-2019, 02:07 AM)Gandalf Wrote: [ -> ]Thanks for your help, and what does the f stand for on your last example?

f stands for 'formatted (string literal)'. It's available from Python 3.6 and you can read about in PEP 498 -- Literal String Interpolation
Got it thanks again for your help.