[Tutor] Dividing a float derived from a string
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
> 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
But that's considered bad practice, it's better to put the
valid errors only in the except line like this:
except TypeError, ValueError:
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
You may not have come across try/except yet, but its a powerful
technique for dealing with these kinds of issues.
Author of the Learn to Program web site
Follow my phopto-blog on Flickr at:
More information about the Tutor