如果在Python中有摩尔质量,如何找到化合物的克数?

2024-10-03 23:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难把摩尔质量换算成克。这个程序显示化合物A的摩尔质量为x克(用户输入)。 如果我有10克二氧化硅,那么硅和氧分别是多少克?在

我该如何对用户输入的10g二氧化硅进行编码,并将其转换为需要多少g的Si和g的O?在

10gSiO2/M二氧化硅*MSi=gSi

2*(10g SiO2/M SiO2)*MO=gO(乘以2,因为O2)

M=摩尔质量

g=克

m=摩尔

import Periodic_Table_new as pt

print("Enter info for Compound A\n")
compoundA = pt.getInput()
gramTotal = float(input("Please enter total grams of Compound A: "))
moles = pt.convertToMoles(gramTotal,compoundA)
moleMass = moles/compoundA
print('\n')
print("The Molecular Mass of compound A at " + str(gramTotal) + "grams is : " + str(moleMass) + "\n\n")

周期表_新建.py在

^{pr2}$

Tags: of用户程序pt质量printgramsstr
2条回答

根据我对你期望的结果的理解,我想出了一个不同的方法。这个版本将使用原子量字典,regex解析复合字符串,并使用循环来计算。它非常灵活,但是它需要你建立原子质量的字典,这不难,只是有点乏味。它对评论中提到的输入有一些要求

import re

atomic_masses = {'Si': 28.0855, 'O': 15.999}

compound = input('Please enter a compound and amount: ')

amount_pat = re.compile(r'(\d+)g')  # compound mass must end in the letter g
element_pat = re.compile(r'([A-Z][a-z]?\d*)')  # elemental symbols must be properly capitalized (Si, not si)
sym_pat = re.compile(r'[A-Z][a-z]?')  # elemental symbols must be properly capitalized (Si, not si)
qty_pat = re.compile(r'\d+')

mass = int(amount_pat.search(compound)[1])

elements = []
# finds each element in the compound and makes a list of (element, parts) tuples
for element in element_pat.finditer(compound):
    element = element[0]
    symbol = sym_pat.search(element)[0]
    if any(c.isdigit() for c in element):
        qty = int(qty_pat.search(element)[0])
    else:
        qty = 1

    elements.append((symbol, qty))

# Calculates and prints total Molecular Mass for the compund
molecular_mass = sum(el[1] * atomic_masses[el[0]] for el in elements)
print(f'\nTotal Molecular Mass: {molecular_mass}\n')

# Calculates and prints the mass for each element
for tup in elements:
    unit_mass = (mass / molecular_mass) * atomic_masses[tup[0]] * tup[1]
    print(f'{tup[0]}: {unit_mass:.4f}g')

输出示例:

^{pr2}$

编辑:

为了适应输入的十进制质量,我们可以将amount_pat中的regex改为r'(\d*.\d+)g'。现在它将接受.003g或{}等值。它仍然不需要kg或mg,但是如果您查找内置的re包,您可以了解regex是如何工作的,并从中进行更改。regex101对于regex也是一个很好的资源,因为它允许尝试和错误的方法来学习。我还在mass赋值语句中将int改为{}

不过,我改变了元素质量环,以适应mg和kg。如果您希望进一步扩展,只需采用我在这里开始的模式并进一步扩展:

for tup in elements:
    unit_mass = (mass / molecular_mass) * atomic_masses[tup[0]] * tup[1]
    if unit_mass > 1000:
        unit_mass /= 1000
        unit = 'kg'

    elif unit_mass < .01:
        unit_mass *= 1000
        unit = 'mg'

    else:
        unit = 'g'

    print(f'{tup[0]}: {unit_mass:.4f}{unit}')

新示例输出:

Please enter a compound and amount: .003g H2O

Total Molecular Mass: 18.01488

H: 0.3357mg
O: 2.6643mg

你需要元素在最后,那是缺失的部分。在

如果没有输入魔法,以下是10g SiO2的示例:

target=10
elem=[['Si',1,28.09],['O',2,16]]

total=0
for e in elem:
  total=total+e[1]*e[2]
print('molar mass of compound:',total)

moles=target/total
print('moles:',moles)

for e in elem:
  print(e[0],moles*e[1],'mol',moles*e[1]*e[2],'g')

相关问题 更多 >