[Tutor] Dividing 1 by another number ?

Tony Meyer tameyer at ihug.co.nz
Mon Jan 31 00:11:11 CET 2005


> I'm trying to write a program they may involve
> needing to divide 1 by another number. In the
> program below when I use 4 for the diameter of
> the bore, and 1 for the diameter of the rod,
> and 60 for the PSI, the  force should be 706.8 .
> However the program keeps giving me 0 for "rodarea".
> If I use a value other than 1 the program works
> fine. am I missing something, this the 3rd program
> I have wrote.
[...]
> PI = 3.14
> area = (bore**2/4)*PI
> rodarea = (rod**2/4)*PI

Dividing two integers will give you an integer (truncated) result:

>>> 1/2
0

Dividing an integer by a float (or vice-versa) will give you a float:

>>> 1/2.0
0.5
>>> 1/float(2)
0.5

If you want '1/2' to give you 0.5 (throughout your script), you can do:

>>> from __future__ import division
>>> 1/2
0.5
>>> 1//2
0

Notice that '//' (with or without the from __future__ import) will give you
the integer result.

=Tony.Meyer



More information about the Tutor mailing list