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

Amit Saha amitsaha.in at gmail.com
Sun Sep 22 02:18:23 CEST 2013


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)

Thanks for any comments.

Best,
Amit.



-- 
http://echorand.me


More information about the Tutor mailing list