division

kpop snag at jool.po
Sun Jun 22 22:41:28 EDT 2003


"Ben Finney" <bignose-hates-spam at and-zip-does-too.com.au> wrote in message
news:slrnbfcp0s.gfb.bignose-hates-spam at iris.polar.local...
> On Mon, 23 Jun 2003 01:44:54 +0100, kpop wrote:
> > Hi, i am writing a maths program where i get input from the user and
> > store it in a string. i then use the eval fucntion to return the right
> > answer.
>
> I wonder what sort of checking you're performing on the input, to
> prevent users typing anything they like and having Python happily eval()
> it.

I will check first that the string olny contains numbers or + - /  * and
 )
if not i wont eval() it i will report an error instead.

>
> > The problem is division, I would like it that only exact division was
> > aloud, I mean no remainders.
>
> Read about math.ceil() and math.floor():
>
>     <http://www.python.org/doc/current/lib/module-math.html#l2h-905>
>     <http://www.python.org/doc/current/lib/module-math.html#l2h-910>

I will

>
> > In python "22 / 5" returs an int of 5
>
> Because both arguments to the division were specified as integers.  If
> you make either argument a floating-point number, the result will also
> be floating-point.
>
> >>> 22 / 5
> 4
> >>> 22.0 / 5
> 4.4000000000000004
> >>> 22 / 5.0
> 4.4000000000000004
> >>> import math
> >>> math.floor( 22 / 5.0 )
> 4.0
> >>>
>
> > i would like if that was illegal because 5 doesnt go into 22 , 4 times
> > exactly, and have the eval function raise an execption which i could
> > handle.
>
> You want different behaviour to the existing arithmetic operators, which
> try to return a meaningful result if possible, rather than raising an
> exception.
>
> > any advice?
>
> I suppose you could create new numeric classes to raise exceptions when
> they received input you don't like, but it seems like a lot of effort.
> Better would be to validate the input better when it is received, so
> that you didn't pass undesired inputs to the arithmetic.
>
> Why not simply math.floor() the result, to force it to an integer?
>
> --
>  \        "Know what I hate most?  Rhetorical questions."  -- Henry N. |
>   `\                                                              Camp |
> _o__)                                                                  |
> http://bignose.squidly.org/ 9CFE12B0 791A4267 887F520C B7AC2E51 BD41714B

thanks for the help, I think i will change all the numbers to floating
points then do the eval
and if the result is not a float that end with..0 i will inform the user
they typed something wrong










More information about the Python-list mailing list