gpt4 book ai didi

python - 名称错误 : name 'ptclType' is not defined

转载 作者:行者123 更新时间:2023-11-30 22:53:59 26 4
gpt4 key购买 nike

我是Python初学者。当我尝试运行下面的代码时,它给出了 NameError。代码的目的是打印 readline 中的单词。我搜索了一些有关此问题的论坛,但找不到合适的解决方案。看来该变量没有出现在 if 语句之外。

import sys
f = open("./multPhiCorr_741_25nsDY_cfi.py",'r')
lines = f.readlines()
if line.find('name') != -1:
Section = line[23:-4] # slice charactor index
print ('[%s]') % Section
if line.find('type') != -1:
ptclType = line[21:-3] # slice charactor index
if line.find('varType') != -1:
nameParVar = line[24:-3] # slice charactor index
if line.find('fx') != -1:
formula = line[21:-3] # slice charactor index
if line.find('etaMin') != -1:
netaMin = line[24:-3] # slice charactor index
print ('{%s 1 eta 1 %s %s}') % (ptclType,nameParVar,formula)

[/u/user/sangilpark/pytest]$ python convert.py
Traceback (most recent call last):
File "convert.py", line 19, in <module>
print ('{%s 1 eta 1 %s %s}') % (ptclType,nameParVar,formula)
NameError: name 'ptclType' is not defined

最佳答案

ptclType 仅在满足条件“if”语句时才定义。因此,当您尝试打印它时,它没有被定义。首先尝试分配默认值:

import sys
f = open("./multPhiCorr_741_25nsDY_cfi.py",'r')
lines = f.readlines()
ptclType = None
nameParVar = None
formula = None
if line.find('name') != -1:
Section = line[23:-4] # slice charactor index
print ('[%s]') % Section
if line.find('type') != -1:
ptclType = line[21:-3] # slice charactor index
if line.find('varType') != -1:
nameParVar = line[24:-3] # slice charactor index
if line.find('fx') != -1:
formula = line[21:-3] # slice charactor index
if line.find('etaMin') != -1:
netaMin = line[24:-3] # slice charactor index
print ('{%s 1 eta 1 %s %s}') % (ptclType,nameParVar,formula)

如您所见,我只是使用默认值(在顶部)定义了 print 语句中的所有内容,以防不满足“if”语句。

关于python - 名称错误 : name 'ptclType' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37963429/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com