2016-06-22 32 views
1

私は初心者です。 以下のコードを実行しようとすると、NameErrorが返されます。 コードの目的は、readlineにwordを出力することです。 これについていくつかのフォーラムを検索しましたが、適切な解決策を見つけることができませんでした。 変数はif文の外側には現れていないようです。NameError:名前 'ptclType'が定義されていません

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 
+0

行に「型」が含まれていない場合、ptclTypeはどうなりますか? –

答えて

3

ptclTypeは、条件付き "if"文が満たされている場合にのみ定義されます。したがって、印刷しようとすると、定義されません。最初のデフォルト値を割り当てるようにしてください:「場合」の文が満たされていない場合には(上部)のデフォルト値を使用してprint文で

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) 

あなたが見ることができるように、私は単純に定義されたすべてのものを。

関連する問題