[Tutor] Error Checking/Defensive Programming

Devin Jeanpierre jeanpierreda at gmail.com
Thu Jan 26 04:49:10 CET 2012


On Wed, Jan 25, 2012 at 10:36 PM, Michael Lewis <mjolewis at gmail.com> wrote:
> Is it generally better to use try/except/else statements or if/elif/else?
> Or, is there a time and place for each?

There's a time and place for each. Most errors are indicated in the
form of an exception being raised, though.

> For a simple example, assume I want a user to enter a number
>
> 1) try:
>        number = float(input('enter a number: ')
>    except ValueError:
>        print('enter a number.')
>    else:
>        print('you entered a number')
>
> OR
>
> 2) number = float(input('enter a number: ')
>     if number >=0 or < 0:
>         print('you entered a number')
>     else:
>          print('enter a number.')
>

float(x) doesn't return anything if the value it's passed can't be
converted to a float. The first way is the only way.

-- Devin


More information about the Tutor mailing list