【问题标题】:How can I convert a user-typed variable from a string to an integer?如何将用户类型的变量从字符串转换为整数?
【发布时间】:2018-04-17 22:51:45
【问题描述】:

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

元素列表

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

【问题讨论】:

  • 你可以像int('0') => 0一样使用int
  • 只需使用Z=int(input("What is the subscript of that element?"))input() 返回的字符串转换为整数即可。提供接受字符串参数的构造函数的其他类型/类也应该可以工作。

标签: python string integer chemistry


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    将您的输入语句包装在一个内置转换函数中。 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] 这将为您提供与用户输入的元素相对应的数字,然后您可以乘以下标。

    【讨论】:

    • 非常感谢!它还告诉我,在我的循环中,“是”没有定义,所以我不能使用它。我该如何定义?
    • YES 不带引号告诉 python 期望变量名 YES 事先定义,你想要的是:while X == 'YES':
    • 我自己构建了一个小型质量计算器,因为我随机觉得它:pastebucket.com/566011
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多