-2

我正在创建一个程序,可以根据元素的原子质量(分别)确定化学式的分子质量。该程序不会运行,因为当我将元素乘以其下标时,它实际上是将字符串与整数相乘。在将元素与下标相乘之前,如何将元素转换为它们的值?

元素列表

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") 
4

2 回答 2

0

python中有用于字段转换的内置方法,例如int(value)将字符串转换为int和float(value)将字符串转换为float。你可以在你的情况下使用它们

于 2018-04-17T23:04:57.917 回答
0

将您的输入语句包装在一个内置的转换函数中。IE。

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] 这将为您提供与用户输入的元素相对应的数字,然后您可以乘以下标。

于 2018-04-17T23:25:00.440 回答