[Tutor] Error Checking/Defensive Programming
Modulok
modulok at gmail.com
Thu Jan 26 05:24:32 CET 2012
It's easier to ask for forgiveness than permission. Ask yourself "Is this an
action that could fail in a specific way?" If yes, you need try/except. If no,
you probably need if/else. When dealing with data such as user input or opening
files and so forth, use try/except. When those actions fail, they fail in
highly specific ways. (No read/write access, no space, invalid user data, etc.)
while True:
try:
number = float(raw_input("Enter a number between 1-10: "))
except ValueError:
print("Error: You need to enter a number.")
else:
# If they got this far, we have a number of some kind.
# Check that it is in the valid range:
if number <= 10 and number >= 1:
# It's valid, stop the loop!
break;
else:
print("Error: Number must be in the range of 1-10.")
print("Yay, the number %.2f!" % number)
On the other hand, if I was looking for an internal condition, I would use
if/else:
win_number = 3
if number == 3:
print("You won!")
else:
print("You loose!")
The rule doesn't always hold true, but it's a general guideline.
Hope that helps.
-Modulok-
On 1/25/12, Michael Lewis <mjolewis at gmail.com> wrote:
> Hi everyone,
>
> I am new to python and have a noob question.
>
> Is it generally better to use try/except/else statements or if/elif/else?
> Or, is there a time and place for each?
>
> 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.')
>
> Thanks for the help.
>
More information about the Tutor
mailing list