[Tutor] Checking that the input is float()-able

Joel Goldstick joel.goldstick at gmail.com
Sun Sep 22 02:26:27 CEST 2013


On Sat, Sep 21, 2013 at 8:18 PM, Amit Saha <amitsaha.in at gmail.com> wrote:

> Hi all,
>
> I want my program to report an error if anything other than a number
> which I can then convert to float using float() is entered as input:
>
> # Python 3
> try:
>     a = float(input('Enter a number: '))
>
> except ValueError:
>     print('Wrong input')
> else:
>     print('Right input')
>
>
> This seems to do the job for me.
>
> python3 input_number.py
> $ Enter a number: 34.563
> Right input
>
> $ python3 input_number.py
> Enter a number: abcd
> Wrong input
>
> $ python3 input_number.py
> Enter a number: {}
> Wrong input
>
>
> I have two queries:
>
> - Is this the best way to do this?
> - Is this is the easiest way to tell a beginner to do this? (Even
> though it introduces try..except)
>

I think its exactly the right way.  Python philosophy is ask for
forgiveness not permission.  This does just that.  Assume things are as you
like and if they aren't, raise an exception.

>
> Thanks for any comments.
>
> Best,
> Amit.
>
>
>
> --
> http://echorand.me
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130921/83e8f89a/attachment.html>


More information about the Tutor mailing list