1

Good afternoon all, I'm new to StackOverflow and Python in general. I'm taking a university course and I'm pretty stumped on pinning down an operand error I'm getting from a very simple calculate-and-return program:

currentYear = 2020
age = input("How old were you in 2020, in numbers? ")

birthYear = currentYear - age

print("Your birth year was: " + str(birthYear))

The error being returned is a TypeError: unsupported operand type(s) for -: 'int' and 'str'

I've tried removing the concatenation in the print, the casting to string, and I've tried putting the calculation of the variables "currentYear" and "age" as strings. I've also tried to force an integer input on the "age" variable by inserting the int(input()) format. It's a very basic issue that I'm overlooking, I'm sure, but I'm at my wits' end!

Bill Hileman
  • 2,798
  • 2
  • 17
  • 24
JWU20
  • 13
  • 5
  • 1
    Your query has already been answered, but this program also has an issue with the time calculation - it'll one year off depending on whether the user has had their birthday yet. – Jiří Baum Oct 07 '20 at 12:19
  • Thanks for the reply. To correct this, should I set the value of "age" as the input minus one? Or should I expand the scope of the question to include the month on a range of 1 - 12? – JWU20 Oct 07 '20 at 12:23
  • Now you're asking the right questions... Dealing with time correctly is hard. – Jiří Baum Oct 07 '20 at 12:40

1 Answers1

1

Welcome! Your issue here is that age is a string, because the input outputs whatever string the user gives. Fortunately you can explicitly make it into an integer, like so:

age = input("How old were you in 2020, in numbers? ")

birthYear = currentYear - int(age)

print("Your birth year was: " + str(birthYear))

Note: this completely ignores the case where your user makes a mistake and the value input is not a number. For example if they input "eight" or something. This is a whole different problem though!

PirateNinjas
  • 1,908
  • 1
  • 16
  • 21
  • Thanks very much for your answer! I misplaced the first line of code, I hope that doesn't change anything about the answer. I understand the issue where the user may not input the correct value - I can prevent that by using the int(input("") format, and by specifying to the user that they need to use integers, right? – JWU20 Oct 07 '20 at 12:22
  • that's correct, yes! The missing line is ok. It was an integer, which I had assumed, so hopefully this will work for you – PirateNinjas Oct 07 '20 at 12:43
  • 1
    Your change did in fact work! I also ran the question by my module tutor once I could get ahold of them and they said either your solution or the int(input("") solution would be equally valid. Thanks again for your help. – JWU20 Oct 07 '20 at 14:17