How can I get the variable to subtract the input please?

Amit Saha amitsaha.in at gmail.com
Tue Nov 19 01:11:10 CET 2013


On Tue, Nov 19, 2013 at 9:56 AM, Ed Taylor <edtaylor63 at gmail.com> wrote:
> This will be very simple to most of you I guess but it's killing me!
>
> print ("Please type in your age")
> age =  input ()
> leave = 16
> print ("You have" + leave - age + "years left at school")
>
> I want to have an input where the users age is inserted and then subtracted from the variable age which is set to 16 and the answer displayed as You have x years left at school.

I assume you are using Python 3. In that case, the input() function
always returns a string:

>>> age = input()
10
>>> age
'10'
>>> age - 10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

And hence you cannot perform a subtraction operation. You will have to
convert the input into a data type such as an integer or a float and
then try to do any mathematical operation:

>>> int(age) - 10
0
>>> float(age)-10
0.0

Hope that helps.

Best,
Amit.


-- 
http://echorand.me



More information about the Python-list mailing list