我有一些困难,试图从莫拉尔质量转换回克。该程序以x克(用户输入)的速度输出化合物A的摩尔质量。如果我有10克SiO2,那么Si和O2是多少克?
我将如何编码用户的输入,比方说10g SiO2,并将其转换为需要多少Si和g O?
10 gSi 2/M SiO2 * MSi =gSi
2*(10克SiO2 /M SiO2) * MO = gO (乘以2,因为O2)
M= Molar质量
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")Periodic_Table_new.py
def getInput():
compoundName = ""
ix = True
total = 0
while ix:
elementName = str(input("Please Enter Element: "))
amountNum = int(input("Please Enter Amount of Element: "))
elementWeight = float(input("Please enter Element Weight: "))
elementWeight = amountNum * elementWeight
total = total + elementWeight
compoundName = compoundName + elementName + str(amountNum)
print(compoundName)
userInput = input("Would you like to repeate? \n Y/N? ")
if userInput == 'N' or userInput == 'n':
ix = False
print(compoundName)
print(total)
return total
def convertToMoles(gOc,c):
moles = gOc/c
return moles
def molesToGrams():
p = moles * n * m发布于 2017-09-27 18:43:56
基于我对你所期望的结果的理解,我想出了一些不同的方法。这个版本将使用原子质量字典、解析复合字符串的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')示例输出:
Please enter a compound and amount: 10g SiO2
Total Molecular Mass: 60.0835
Si: 4.6744g
O: 5.3256g编辑:
为了适应输入的十进制质量,我们可以将amount_pat内部的正则表达式更改为r'(\d*.\d+)g'。现在它将接受诸如.003g或0.003g之类的值。它仍然不需要kg或mg,但是如果您查找内置的re包,您可以了解regex是如何工作的,并从那里更改它。regex101也是regex的一个很好的资源,因为它允许尝试和错误的学习方法。我还在int赋值语句中将mass更改为float
然而,我确实改变了元素质量循环来调整镁和千克。如果您希望进一步扩展它,只需采用我在这里开始的模式,并进一步扩展它:
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发布于 2017-09-27 17:50:30
你将需要元素的结尾,这是缺少的部分。
如果没有输入魔法,下面是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')发布于 2022-10-12 11:12:04
计算复合中元素的摩尔质量和质量百分比
我使用比伐仑包来实现您想要的输出。这是我的密码
from pyvalem.formula import Formula
import numpy as np
def give_compound_details(compound, given_gram):
# Dictionary of element of mole of a compound
ele_mol_dict = Formula(compound).atom_stoich
# Create a list comprehensioon to get the mass per ele
mass_per_ele = [Formula(ele).mass * ele_mol_dict[ele] for ele in ele_mol_dict.keys()]
# Create dic for ele and mass
ele_mass_dict = dict(zip(list(Formula(compound).atom_stoich),mass_per_ele))
# Create a list comprehension and dictionary for mass percentage per element of a compound
ele_percent_mass_dict = dict(zip(list(ele_mol_dict.keys()),[(ele_mass_dict[ele] / Formula(compound).mass * 100) for ele in ele_mass_dict.keys()]))
print(f"Total Molecular mass of {compound}: {Formula(compound).mass} g\n")
for key, value in ele_mass_dict.items():
print(f"Molar Mass of {key}: {value} g")
print("")
for key, value in ele_percent_mass_dict.items():
print(f"Mass Percentage of {key}: {round(value,2)} %")
print("")
print(f"If molecular mass of {compound} is {given_gram} g, therefore")
for key, value in ele_percent_mass_dict.items():
print(f"Mass of {key}: {round((value/100)*given_gram,4)} g")
# MAIN PROGRAM
is_running = True
while is_running:
print("Computing the Molar Mass and Mass Percentage of Elements within a Compound")
print("")
compound = input("Compound: ")
given_gram = float(input(f"How much {compound} do you have in grams? "))
print("\nRESULT\n")
function = give_compound_details(compound, given_gram)
print("---------------------------------------")
ask = input('Do you want to try again? \nType "y" is YES, type "n" if NO')
if ask.islower() == 'n':
is_running = False
print("---------------------------------------")下面是示例输出:输出截图
https://stackoverflow.com/questions/46452626
复制相似问题