[Tutor] Dividing a float derived from a string

Alan Gauld alan.gauld at btinternet.com
Fri Nov 21 01:23:42 CET 2014


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




More information about the Tutor mailing list