The first 10 elements of the periodic table and some of their properties can be found in Table 2 These elements can be combined to create molecules. For example, two hydrogen atoms (2H) can be added to an oxygen (O) atom to create a water molecule (H2O). This combination can be written as 2H + 1O → H2O 1 (or more commonly H2O).
Write a Python program that can add elements together. Your program should:
-
Ask the user to enter a string of the form xA + yB + zC + …, where x, y, and z are positive integers (called stoichiometric coefficients) and A, B, and C are distinct symbols of elements. Examples include 2H + 1O and 1C + 2O. The user should be asked to enter the string again if a stiochiometric coefficient is not a positive integer, or if a symbol does not match any of the elements in Table 2. The formula for the molecule should then be printed to the screen as AxByCz (e.g. C2H4). If any of the stoichiometric coefficients are 1, then they should not be printed (e.g. H2O1 should be H2O, C1O2 should be CO2).
-
Calculates the atomic mass of the molecule. The atomic mass of a molecule is equal to the sum of the atomic masses of each element present in the molecule multiplied by the stoichiometric coefficient for that element. This value should be printed to the screen.
Table 2:: The first 10 elements of the periodic table.
Element | SymbolAtomic mass | |
---|---|---|
Hydrogen | H | 1 |
Helium | He | 4 |
Lithium | Li | 7 |
Beryllium | Be | 9 |
Boron | B | 11 |
Carbon | C | 12 |
Nitrogen | N | 14 |
Oxygen | O | 16 |
Fluorine | F | 19 |
Neon | Ne | 20 |
Ps:The only computing library we can use is math
The codes are showed in the following:
ma = ['H','He','Li','Be','B','C','N','O','F','Ne']
mass = {'H':1,'He':4,'Li':7,'Be':9,'B':11,'C':12,'N':14,'O':16,'F':19,'Ne':20}
start = 0
while start != 1:
elements = input("xA + yB + zC + ..., where x, y, and z are positive integers (called stoichiometric coefficients) and A, B, and C are distinct symbols of elements.
" )
elements = elements.split("+")
#print(elements)
toss = 0
length = len(elements)
fangcheng = ''
for i in range(length):
divide = list(elements[i])
adivide = ''.join(divide[-2:])
if divide[-1] in ma:
xishu = int(elements[i].replace(divide[-1], ''))
toss = toss + xishu * mass[divide[-1]]
if xishu == 1:
fangcheng = fangcheng + divide[-1]
else:
fangcheng = fangcheng + divide[-1] + str(xishu)
start = 1
elif adivide in ma:
xishu = int(elements[i].replace(adivide,''))
toss = toss + xishu * mass[adivide]
if xishu == 1:
fangcheng = fangcheng + adivide
else:
fangcheng = fangcheng + adivide + str(xishu)
strat = 1
else:
print("Input error, please re-enter")
print(fangcheng)
print(toss)