Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What have I done wrong?
#1
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
Reply
#2
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. ')
Reply
#3
Thanks for your help, and what does the f stand for on your last example?
Reply
#4
(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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#5
Got it thanks again for your help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,385 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  python gives wrong string length and wrong character thienson30 2 2,941 Oct-15-2019, 08:54 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020