Ask coding questions

← Back to all posts
Why doesn't this work?
shazbot (0)

Using Python, this is my code (This is actually from a college course)

age = input("How old are you ")
print("You are", age, "years old.")
print("You have", 65 - age, "years until you can retire.")

I get this error after I enter my age:

Traceback (most recent call last):
File "main.py", line 3, in <module>
print("You have", 65 - age, "years until you can retire.")
TypeError: unsupported operand type(s) for -: 'int' and 'str'

I've tried to edit it a bunch of different ways, but I can't get it to perform this simple calculation.

Answered by ArchieMaclean (584) [earned 5 cycles]
View Answer
Commentshotnewtop
ArchieMaclean (584)

When you get an input using input, the type is a str (string - text). That means that age is a string - a piece of text.

Then, when you do 65-age, it's trying to take away a string from a number - and that doesn't work.

To fix, change to 65 - int(age) - that converts the age to a whole number (integer), then subtracts it.
So the fixed code is:

age = input("How old are you ")
print("You are", age, "years old.")
print("You have", 65 - int(age), "years until you can retire.")

Please mark this as the answer if it solved your problem :)

shazbot (0)

@ArchieMaclean that worked, thank you for the explanation :).