我正在创建一个程序,可以根据元素的原子质量(分别)确定化学式的分子量。程序将不会运行,因为当我将元素乘以其下标时,它实际上是将字符串与整数相乘。如何在将元素与下标相乘之前将元素转换为它们的值?
M={"H":1.01, "He":4.0, "Li": 6.9, "Be":9.0, "B":10.8, "C":12.0, "N":14.0,
"O":16.0, "F":19.0, "Ne":20.2, "Na":23.0, "Mg":24.3, "Al":27.0, "Si":28.1,
"P":31.0, "S":32.1, "Cl":35.5, "Ar":40.0, "K":39.1, "Ca":40.1, "Sc":45.0,
"Ti":47.9, "V":50.9, "Cr":52.0, "Mn":54.9, "Fe":55.8, "Co":58.9, "Ni": 58.7,
"Cu":63.5, "Zn":65.4, "Ga":69.7, "Ge":72.6, "As":74.9, "Se": 79.0, "Br":
79.9,"Kr":83.8, "Rb":85.5, "Sr":87.6, "Y":88.9, "Zr":91.2, "Nb":92.9,
"Mo":95.9, "Tc":98.0}
#Now we can create our loop to add the molar masses
M=input("What is your first element/symbol")
Z=input("What is the subscript of that element?")
C= M*Z
X= input(str("Do you have another element? Type YES to continue and NO to
stop"))
while X==(str(YES)):
M=input("What is your first element/symbol")
B=input("What is the subscript of that element")
D==M*B
X==input(str("Do you have another element? Type YES to continue and No
to stop"))
else:
print("Your molar mass is", C+D, "g/mol")
答案 0 :(得分:0)
python中有一些用于字段转换的内置方法,如int(value)将字符串转换为int,float(value)将字符串转换为float。您可以在案例中使用它们
答案 1 :(得分:0)
将输入语句包装在其中一个内置转换函数中。 即。
M=str(input("What is your first element/symbol"))
Z=int(input("What is the subscript of that element?"))
这会将用户的输入转换为您想要的格式。 (实际上不需要转换为字符串,因为这是默认值)
与您的问题无关的另一件事是,您将要改变使用该词典的方式。也许将它定义为M_dict,然后使用用户输入的M来引用它,就像这个M_dict [M] 这将为您提供与用户输入的元素相对应的数字,然后您可以乘以下标。