[Tutor] exceptions problem

Dave Angel davea at ieee.org
Fri Sep 10 17:52:32 CEST 2010


  On 2:59 PM, Roelof Wobben wrote:
> <snip>
> Now I thought this would work:def readposint():
>      x = raw_input("Please enter a positive integer :")
>      try:
>          x = int(x) and x>  0
>      except:
>          print x , "is not a positive integer.  Try again."
>          return False
>      return Truey = readposint()
> prin<snip>

There's no exception triggered by the valid expression
    x = int(x) and x > 0

when x is negative.  That's a perfectly valid expression, as long as the 
string is valid numeric.  It doesn't set x to  what you might expect, 
though - try it with x = "3".

Leave the try statement around the int(x), which can indeed throw an 
exception.  But you need a separate  if statement to test whether x is 
greater than zero.

DaveA



More information about the Tutor mailing list