[Tutor] Dividing a float derived from a string
Stephanie Morrow
svmorrow at gmail.com
Fri Nov 21 14:19:59 CET 2014
Alan,
I am getting a syntax error when I print the following:
input = raw_input("Insert a number: ")
try:
print float(input) * 12
except: TypeError, ValueError:
print False
The "try" is coming up as red. Any idea why?
On Fri, Nov 21, 2014 at 12:23 AM, Alan Gauld <alan.gauld at btinternet.com>
wrote:
> On 20/11/14 21:20, Stephanie Morrow wrote:
>
> input = raw_input("Insert a number: ")
>> if input.isdigit():
>> print int(input) * 12
>> else:
>> print False
>>
>> /However/, a colleague of mine pointed out that a decimal will return as
>> False. As such, we have tried numerous methods to allow it to divide by
>> a decimal, all of which have failed. Do you have any suggestions?
>> Additionally, we are using 2.7, so that might change your answer.
>>
>
> The simplest solution is simply to convert it to a floating point number
> instead of an integer. float() can convert both integer and floating
> point(decimals) strings top a floating point number.
>
> But how do you deal with non numbers?
> In Python we can use a try/except construct to catch anything that fails
> the conversion:
>
> try:
> print float(input)*12
> except:
> print False
>
> But that's considered bad practice, it's better to put the
> valid errors only in the except line like this:
>
> try:
> print float(input)*12
> except TypeError, ValueError:
> print False
>
> So now Python will look out for any ValueErrors and TypeErrors
> during the first print operation and if it finds one will instead
> print False. Any other kind of error will produce the usual Python error
> messages.
>
> You may not have come across try/except yet, but its a powerful technique
> for dealing with these kinds of issues.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my phopto-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20141121/400c7ae7/attachment.html>
More information about the Tutor
mailing list