do you guys help newbies??
Robin Munn
rmunn at pobox.com
Wed Nov 27 13:56:32 EST 2002
Wojtek Walczak <gminick at hacker.pl> wrote:
> Dnia Wed, 27 Nov 2002 15:53:20 GMT, Robin Munn napisa³(a):
>> You could also do this in one step, like:
>> gallonsPerTank = int(raw_input("Enter how many gallons..."))
> It of course works, but there's a large amount of situations to think of.
>
> ---
> import sys
> try:
> while 1:
> a = raw_input("Put a digit here: ")
> if not a.isdigit():
> a = raw_input("Put a digit here: ")
> else:
> a = int(a)
> break
> except:
> print sys.exc_info()[1]
> sys.exit()
>
> print a
> ---
>
> Any ideas to make it more reliable ?
>
You're trying too hard. Let Python do the error-catching for you.
try:
a = int(raw_input('Enter your number: '))
except ValueError:
print "I asked for a number."
Or, if you want to loop until the user types in valid input:
while 1:
try:
a = int(raw_input('Enter your number: '))
except ValueError:
print "That wasn't a number."
else:
break
This is almost exactly like the code you posted, except that the
isdigit() test was completely unnecessary. Let int() catch your errors
for you -- that's what exceptions are for.
--
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838 50FF 2478 CFFB 081A 8338 54F7 845D ACFD 6AFB 6838
More information about the Python-list
mailing list