<html>
<head>
<style><!--
.hmmessage P
{
margin:0px;
padding:0px
}
body.hmmessage
{
font-size: 10pt;
font-family:Tahoma
}
--></style>
</head>
<body class='hmmessage'>
<BR> <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>> ...<BR>> def readposint():<BR>> x = raw_input("Please enter a positive integer :")<BR>> try:<BR>> if not (x == int(x) and x< 0): raise(ValueError)<BR>> except:<BR>> print x , "is not a positive integer. Try again."<BR>> return False<BR>> return True<BR>><BR>> y = readposint()<BR>> print y<BR>> while y == False:<BR>> readposint()<BR>> print "You have entered : ", y<BR>><BR>> 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)<0 or (float(x) - int(x) > 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)<0 or (float(x) - int(x) > 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>><BR>> 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> </PRE><BR>_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor                                            </body>
</html>