On Sat, Sep 21, 2013 at 8:18 PM, Amit Saha <amitsaha...@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@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to