Molecular Weight
Enter a chemical formula, or just the enter key to quit: C2H5OH
The molecular weight is 46.0688
Enter a chemical formula, or just the enter key to quit: COOHC6H4OCOCH3
The molecular weight is 180.1598
Enter a chemical formula, or just the enter key to quit: C9H804
The molecular weight is 180.1598
Enter a chemical formula, or just the enter key to quit: C8H18
The molecular weight is 114.2302
Enter a chemical formula, or enter key to quit:def print_map(map):
for element in map:
print (str(element) + ": " + str(map[element]))
def calc_atomic_weight(map):
tit
for element in map:
print (str(element) + ": " + str(mol_count[element]))
print("The molecular weight is ")
# begin program
while True:
# dictionary to store the occurances of molecular elements
# the count of each element gets initialized to zero
mol_count = { 'O':0, 'H':0, 'C':0 }
number = "";
user_in = input("Enter a chemical formula, or just the enter key to quit: ")
# user string was empty
# quit the program
if (not user_in):
break
# otherwise begin analysis on the string
i = 0
while(i < len(user_in)):
# we expect the first occurance to be a capital letter
# of 'O' 'C' or 'H' *that is, exist within the dictionary*
iter_char = user_in[i]
if iter_char in mol_count:
# the next occurance must either be another
# character or a sequence of digits
j = i + 1
if(j < len(user_in) and user_in[j].isdigit()):
while(j < len(user_in) and user_in[j].isdigit()):
number += user_in[j]
j += 1
# continue where we left off
i = j
else:
number = "1"
i += 1
else:
print("Badly formed molecular formula; try again.")
break
# increment appropriate molecule
mol_count[iter_char] += int(number)
number = "";
#print_map(mol_count)
calc_atomic_weight(mol_count)Last updated