Reputation: 98
I am writing a program to calculate the mass of a given molecule. I have defined every element as an integer. I need to be able to type in a chemical formula like NaCl and have it print out the sum of the atomic masses of Na and Cl. So far I have things set up so that I can type in a chemical formula and it turns it into a list of elements, so if I typed in NaCl it would give me ['Na', 'Cl']. Here is the code:
import re
Na = 22.99
Cl = 35.45
input = raw_input()
inputList = (re.findall('[A-Z][^A-Z]*', input))
Firstly I need to know how to tell the computer I am inputting variables that I previously defined, not strings. Then I want to make it assign each item from the list to its own variable. Something like
e1 = Na
e2 = Cl
My main issue is that at the moment my input is treated as a string.
Upvotes: 1
Views: 91
Reputation: 49330
Use the sum()
and map()
functions to add up the appropriate values from a dictionary:
>>> elements = {'Na':22.99, 'Cl':35.45}
>>> result = ['Na', 'Cl']
>>> answer = sum(map(elements.get, result))
>>> answer
58.44
Upvotes: 2
Reputation: 53663
Using a dictionary, you can easily take string input and handle it:
elements = { 'Na': 22.99,
'Cl': 35.45
} # You can extend this dictionary to include more elements
print elements.get(raw_input('Enter an element symbol: ', 'invalid'))
"""
use the .get method to return a placeholder value,
representing that the *input* value doesn't exist in the dictionar
"""
Upvotes: 1
Reputation: 77910
I believe what you want is a dictionary, like so:
atomic_wt = {'Na':22.99, 'Cl':35.45}
Later, when you have your inputs, you can access them in a loop:
for element in inputList:
elem_wt = atomic_wt[element]
Upvotes: 2