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

alex23 wuwei23 at gmail.com
Mon Nov 18 19:22:40 EST 2013


On 19/11/2013 9:56 AM, Ed Taylor 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.
>
> Help much appreciated.

Hey there,

When asking code questions, if you get a traceback it's often handy to 
include it so we can see exactly what problem you've hit.

Luckily, it's pretty obvious here:

1. input() binds a string to 'age', whereas 'leave' is an integer; you 
cannot subtract a string from an integer, you need to turn the string 
into an integer first. Try:

     age = int(input())

2. With this done, you still have a similar issue: 'leave - age' 
produces an integer, and you cannot concatenate strings & integers. You 
can use string formatting to take care of this:

     print("You have {} years left at school".format(leave - age))

There's a lot more to formatting than this, make sure to check out the 
docs for it:

http://docs.python.org/3.1/library/string.html#format-string-syntax

Hope this helps.




More information about the Python-list mailing list