[Tutor] Re: program?

Andrei project5 at redrival.net
Sat Dec 6 19:21:58 EST 2003


Jacques wrote on Sat, 06 Dec 2003 17:27:55 -0500:

> I dont know if you would call this a program. Please let me know if it 

Any piece of code qualifies as a program. Just a file containing "pass" is
a program. It's just not particularly useful.

> qualifies to be a program. I just started with python and started 
> programming. So, please bare with me.
>  >>> # Perimeter of a rectangle equals sum of width times two, plus sum 
> of lenth times 2.
>  >>> width = 8 #inches
>  >>> length = 1 #foot
>  >>> (width * 2) + (length * 2)
> 18
>  >>> # answer is incorrect, because inches and feet are not same unit.

Python doesn't know units. If you tell it to add 3 #pears to 4 #apples and
give you the result in #strawberries, it will happily say 7; #something is
just a comment, not a unit. You have to implement code for unit conversion
on your own. 

> How would I be able to fix that?

You could do this quite easily by just picking one standard value (e.g. the
meter since using SI units internally is the only sane thing to do if you
don't want to end up shooting yourself in the foot - no pun intended) and
defining constants like this (I don't define them very accurately, you
might want to pull more decimals in there):

>>> inch = 0.025 # 1 in is about 2.5 cm
>>> foot = 0.30 # 1 ft is about 30 cm

This way you could convert quite easily between archaic units, where
in-memory everything is stored in a standard unit:

>>> width = 8*inch # just write the unit as you'd usually do, 
                   # but add "*". 8 times one inch, which is really
                   # what "8 in" means anyway.
>>> length = 1*foot
>>> perimeter = 2*(width+length) # in memory stored as meters
>>> print "perimeter is", perimeter/foot, "ft" # give perimeter in ft
perimeter is 3.33333333333 ft
>>> 8*inch/foot # convert 8 in to ft; "/" works like "convert to"
0.66666666666666674
>>> 8*foot/inch # convert 8 ft to in
95.999999999999986
>>> 9.81/inch # gravity as in/s^2
392.39999999999998

There's also at least one Python module which can work with units, but I
don't remember what it's called - anyway, it would be overkill for such
simple cases.

-- 
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list