faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 1 of 2 people (50%) answered Yes

Entry

Assistance on first program (molecular mass)

Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 49, Terry Reedy


"""
Packages: oop;miscellaneous
"""

"""
>ok I am very new to python and am trying to make my first program... its
>a program that tells the Molecular Mass of an object.. by inputting the
>amount of the element in variables for example
>
>o = 12.0110
>
>h = 1.0
>
>I want to be able to put h in the imput screen and receive 1.0 also.. be
>able to add h and o together and receive the numerical results... and
>then allow them to be multiplied by numbers..
>
>basic input would be "2*h+o
>and results would be... 14.0110

I'll give you a start:
"""

class atom:
  def __init__(self, atomic_weight):
    self.aw = atomic_weight
  def __add__(self,other):    return self.aw + other.aw
  def __radd__(self, number): return number + self.aw
  def __rmul__(self,number):  return number * self.aw

h = atom(1.0)
o = atom(12.011)
# etc
print 2*h+o
# prints 14.011