[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Help a noob out

On Thu, May 2, 2019 at 5:26 AM <felixen989 at hotmail.co.uk> wrote:

> Hey guys, can someone quickly explain why this piece of code doesn't work?
> (I'm really new to Python)
> birth_year = input("What year are you born? ")
> current_year = 2019
> age = current_year - birth_year
> print(age)
> --
> https://mail.python.org/mailman/listinfo/python-list

input() returns a string. So the user enters "1978" for example but he
could just have easily entered "Honda Civic". Python doesn't know to
interpret it as a number in order to do arithmetic or it until you convert
it to an integer.

birth_year = int(input("What year were you born?")) should work, unless I
missed something else.

(the int() converts the string to an integer)

Maybe it would be more professional to do some error checking though, e.g.
print that there was incorrect input and ask again if they didn't actually
input an integer. You could do this using the try and except keywords (in
some kind of loop), as int() raises an exception when the string you pass
it isn't an actual integer.