在循环中使用和序列来计算值

我需要有关编写的用于使用化学计量计算密度的代码的帮助。每次执行时,它将创建一个唯一的文本文件,并在每个唯一的文本文件中写入对应于密度的化学计量。因此,一旦第一次执行,“ stoich”将变为2,然后变为4,依此类推。它写入的每个文本文件将具有计算出的密度的不同“ stoich”值。

  den_U = 19.1 #density of uranium 238 g/cc
  den_C = 2.26 #density of carbon 12 g/cc

  molm_U = 238.02 #molar mass of Uranium g/mol
  molm_C = 12.0107 #molar mass of Carbon g/mol

  stoich = [1,2,4,10,100,200,500,1000,2500,3000,4000]


  for i in stoich:
      input = 'density_stoichiometry_'+str(d)+'_'
      file = open(input + '.txt','w')

      T_C = molm_C*stoich # calculates total mass of carbon 
      T_com = T_C + molm_U # calculates total mass of chemical compound
      per_C = T_C/T_com # calculates percent of carbon in compound
      per_U = molm_U/T_com #calculates the percent of uranium in compound
      den_com = den_U*per_U + den_C*per_C # calculates the total density 
      d = stoich

      file.write('density='+str(den_com)+ '\n')  
      file.write('stoichiometry=' +str(d)+ '\n')
      file.close()

      stoich = 1

代码给了我'T_C = molm_C * stoich'的错误,说我不能将序列乘以'float'类型的非整数。我假设我在“ d = stoich”时也会遇到同样的问题。如果有人可以提供帮助,我将不胜感激。

chenzhao5001 回答:在循环中使用和序列来计算值

以下作品:

den_U = 19.1 #density of uranium 238 g/cc
den_C = 2.26 #density of carbon 12 g/cc

molm_U = 238.02 #molar mass of Uranium g/mol
molm_C = 12.0107 #molar mass of Carbon g/mol

stoich = [1,2,4,10,100,200,500,1000,2500,3000,4000]


for i in stoich:
  fname = 'density_stoichiometry_'+str(i)+'_.txt'
  file = open(fname,'w')

  T_C = molm_C*i # calculates total mass of carbon 
  T_com = T_C + molm_U # calculates total mass of chemical compound
  per_C = T_C/T_com # calculates percent of carbon in compound
  per_U = molm_U/T_com #calculates the percent of uranium in compound
  den_com = den_U*per_U + den_C*per_C # calculates the total density 

  file.write('density='+str(den_com)+ '\n')  
  file.write('stoichiometry=' +str(i)+ '\n')
  file.close()

我在循环体中使用了i而不是stoich,摆脱了毫无意义的d,并替换了input(内置名称函数)与fname。我还将fname的定义合并到了一行,因为它降低了可读性,将其定义分为两行(其定义的一部分嵌入在函数调用中)。

本文链接:https://www.f2er.com/3136488.html

大家都在问