[Tutor] Dividing a float derived from a string

Stephanie Morrow svmorrow at gmail.com
Fri Nov 21 14:23:57 CET 2014


This one worked!  Thank you very much! :D

On Fri, Nov 21, 2014 at 3:14 AM, Adam Jensen <hanzer at riseup.net> wrote:

> On Thu, 20 Nov 2014 21:20:27 +0000
> Stephanie Morrow <svmorrow at gmail.com> wrote:
>
> > Hi there,
> >
> > I have been posed with the following challenge:
> >
> > "Create a script that will ask for a number. Check if their input is a
> > legitimate number. If it is, multiply it by 12 and print out the result."
> >
> > I was able to do this with the following code:
> >
> > 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.
> >
> > Thank you in advance for any help you can provide!
> >
> > -Stephanie
>
> How about using a floating point type cast to convert the string to a
> number within a try/except block? Maybe something like this:
>
> try:
>     x = float(input("Enter a number: "))
>     print(x * 12)
> except ValueError:
>     print("Not a valid number.")
>
> A little enhancement might involve removing any spaces from the string so
> something like '5.6 e -3' will also be valid input. Like this:
>
> x = float(input("Enter a number: ").replace(' ',''))
> _______________________________________________
> 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/ec5f5263/attachment.html>


More information about the Tutor mailing list