首页 > 解决方案 > 在循环中使用和序列来计算值

问题描述

我需要关于我编写的使用化学计量计算密度的代码的帮助。每次执行时,它将创建一个唯一的文本文件,并在每个唯一的文本文件中写入与密度相对应的化学计量。因此,一旦它第一次执行,“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' 处给了我错误,说我不能将序列乘以非 int 类型的 'float'。我假设我在“d = stoich”也会遇到同样的问题。如果有人可以提供帮助,我将不胜感激。

标签: pythonloops

解决方案


以下作品:

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一行,因为将其定义分成两行(其中部分定义嵌入在函数调用中)会降低可读性。


推荐阅读