[Tutor] exceptions problem
Francesco Loffredo
fal at libero.it
Fri Sep 10 20:23:09 CEST 2010
On 10/09/2010 18.12, Roelof Wobben wrote:
> ...
> def readposint():
> x = raw_input("Please enter a positive integer :")
> try:
> if not (x == int(x) and x< 0): raise(ValueError)
> except:
> print x , "is not a positive integer. Try again."
> return False
> return True
>
> y = readposint()
> print y
> while y == False:
> readposint()
> print "You have entered : ", y
>
> But -9 and 2 are both true.
My fault, I didn't notice that after raw_input, whatever you enter is a
STRING, not an integer! So, without any exception thrown, the comparison
x == int(x) is always False. Let's make it better:
if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
Then, if the input value x is indeed a positive integer, you should
return x, not True or False. Try returning -1 if the exception is
thrown, in line 7, and returning x in line 8. Then, you should change
also line 12... ok, here's to you:
def readposint():
x = raw_input("Please enter a positive integer :")
try:
if (int(x)<0 or (float(x) - int(x) > 0)): raise(ValueError)
except:
print x , "is not a positive integer. Try again."
return -1
return x
y = readposint()
print y
while y == -1:
readposint()
print "You have entered : ", y
>
> Roelof
Francesco
-------------- next part --------------
Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com
Versione: 9.0.851 / Database dei virus: 271.1.1/3124 - Data di rilascio: 09/09/10 08:34:00
More information about the Tutor
mailing list