<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 10pt;
font-family:Tahoma
}
--></style>
</head>
<body class='hmmessage'>
<BR>&nbsp;<BR>Date: Fri, 10 Sep 2010 20:23:09 +0200<BR>From: fal@libero.it<BR>To: tutor@python.org<BR>Subject: Re: [Tutor] exceptions problem<BR><BR><PRE>On 10/09/2010 18.12, Roelof Wobben wrote:<BR>&gt; ...<BR>&gt; def readposint():<BR>&gt;         x = raw_input("Please enter a positive integer :")<BR>&gt;         try:<BR>&gt;               if not (x == int(x) and x&lt;  0): raise(ValueError)<BR>&gt;         except:<BR>&gt;                 print x , "is not a positive integer.    Try again."<BR>&gt;                 return False<BR>&gt;         return True<BR>&gt;<BR>&gt; y = readposint()<BR>&gt; print y<BR>&gt; while y == False:<BR>&gt;         readposint()<BR>&gt; print "You have entered : ", y<BR>&gt;<BR>&gt; But -9 and 2 are both true.<BR>My fault, I didn't notice that after raw_input, whatever you enter is a <BR>STRING, not an integer! So, without any exception thrown, the comparison<BR>x == int(x) is always False. Let's make it better:<BR>    if (int(x)&lt;0 or (float(x) - int(x) &gt; 0)): raise(ValueError)<BR> <BR> <BR>Then, if the input value x is indeed a positive integer, you should <BR>return x, not True or False. Try returning -1 if the exception is <BR>thrown, in line 7, and returning x in line 8. Then, you should change <BR>also line 12... ok, here's to you:<BR> <BR>def readposint():<BR>     x = raw_input("Please enter a positive integer :")<BR>     try:<BR>         if (int(x)&lt;0 or (float(x) - int(x) &gt; 0)): raise(ValueError)<BR>     except:<BR>         print x , "is not a positive integer.    Try again."<BR>         return -1<BR>     return x<BR> <BR>y = readposint()<BR>print y<BR>while y == -1:<BR>     readposint()<BR>print "You have entered : ", y<BR> <BR>&gt;<BR>&gt; Roelof<BR>Francesco</PRE><PRE>Thank you.</PRE><PRE>I never thought that you can use a float and a integer to look if the number is a integer.</PRE><PRE>Roelof</PRE><PRE><BR>&nbsp;</PRE><BR>_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor                                               </body>
</html>