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

Andrew Berg robotsondrugs at gmail.com
Mon Nov 18 19:20:31 EST 2013


On 2013.11.18 17:56, 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.
> 
> Thank you
> 
You provided a short code snippet to help describe your problem, which is good, but you omitted what happened and what you expected. You
also didn't mention which version of Python you're using (I am going to assume some 3.x; if you are using 2.x, I *strongly* recommend
switching to 3.x unless you have a very compelling reason not to). If a traceback is printed, try to make sense of it, and if you can't,
post it in its entirety and ask us to explain it.
>From what I can tell, you are trying to mix integers with strings. Python is strongly typed; it won't try to guess what you want when you
try to do things that make no sense for a given type. input() returns a string and you have defined leave as an integer. Using the +
operator to concatenate makes sense for strings, but it makes sense to do addition when dealing with number types like integers and floats.
If you try to do something silly like add a number to a string, Python will complain because it doesn't know what to do (and again, it won't
try to guess). With that in mind, rewrite the code so that you do number operations on numbers and string operations on strings.
Hint: there are builtin functions to cast between types.
Hint 2: it's a good idea to split up operations to separate lines so that it's easy to see which operation has a problem if there is one.

-- 
CPython 3.3.2 | Windows NT 6.2.9200 / FreeBSD 10.0



More information about the Python-list mailing list