首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >‘必须是实数,不是str’问题

‘必须是实数,不是str’问题
EN

Stack Overflow用户
提问于 2022-01-15 16:08:21
回答 1查看 102关注 0票数 0

我试图用研究门的代码(DOI: 10.1039/C9CP01704F)计算分子的介电常数。对于某些分子,它工作得很完美,但对于有些分子,我得到的错误是:必须是实数,而不是str。

输入文件包含分子的微笑扩展。

代码语言:javascript
复制
import sys, math, scipy.constants as sp
from collections import Counter
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors
代码语言:javascript
复制
def get_dielectric_constant(mol, TK, Vm, nD):
    gu2 = get_calc_gmu2(mol)
    if type(gu2) is str: return gu2
    x = alpha * gu2 / (TK * Vm)
    a = nD**2
    Delta2 = 8*a**2 + (a + x*(a+2)**2)**2
    DC = 0.25*(a + x*(a+2)**2 + math.sqrt(Delta2))
    return DC
代码语言:javascript
复制
def get_output_line(density, Vm, nD, dc):
    if type(density) is float:
        line = '%5.3f %6.1f' %(density, Vm)
    else:
        line = '%s %s' %(str(density), str(Vm))
    if type(nD) is float:
        line += ' %6.3f' %nD
    else:
        line += ' %s' %str(nD)
    try:
        line += ' %8.4f' %dc
    except ValueError:
        line += ' %s' %str(dc)
    return line
代码语言:javascript
复制
Traceback (most recent call last):
  File "C:\Users\Admin\Downloads\c9cp01704f2\smi2DC.py", line 370, in <module>
    print(get_output_line(density, Vm, nD, dc))
  File "C:\Users\Admin\Downloads\c9cp01704f2\smi2DC.py", line 340, in get_output_line
    line += ' %8.4f' %dc
TypeError: must be real number, not str

Process finished with exit code 1

有人知道怎么解决这个问题吗?

EN

回答 1

Stack Overflow用户

发布于 2022-01-15 16:23:03

看起来dcget_output_line()中可能是一个字符串,是预期的吗?您的代码不处理这种情况-- ' %8.4f' % dc要求dc是一个数字。

也许你是想用一个ValueError代替TypeError?还是对dc使用与其他变量相同的dc成语?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70723132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档