[Tutor] Dividing a float derived from a string

Adam Jensen hanzer at riseup.net
Fri Nov 21 23:21:14 CET 2014

> -----Original Message-----
> From: Tutor [mailto:tutor-bounces+hanzer=riseup.net at python.org] On
> Behalf Of Alan Gauld
> Sent: Thursday, November 20, 2014 7:24 PM

> But that's considered bad practice, it's better to put the valid errors
only in
> the except line like this:
> try:
>      print float(input)*12
> except TypeError, ValueError:
>      print False
> 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 messages.
> You may not have come across try/except yet, but its a powerful technique
> for dealing with these kinds of issues.

I'm browsing the built-in
[exceptions](docs.python.org/3.4/library/exceptions.html) and reading about
the [float cast](docs.python.org/3.4/library/functions.html#float) and it
seemed like it might be a good idea to catch overflows, so:

    print(float(input('Enter a number: ').replace(' ','')) * 12)
except ValueError:
    print('Not a valid number.')
except OverflowError:
    print('Too big!')
except EOFError:

I guess TypeError isn't necessary since input() returns a string and that's
a valid type for float(). EOFError is there to handle ^D gracefully.
Curiously, a float cast on a very large number represented as a string
returns 'inf' rather than raising an overflow error. I didn't expect that. 

More information about the Tutor mailing list