我遇到了一个问题,尝试...其他...我正在测试使用try
设置了一个变量。如果尚未设置,我只想继续循环。如果已设置变量,我想运行else
部分。但是,Python会因为尝试在else
部分执行操作而失败,因为该变量尚未设置,因此会出现抖动。有点像Catch-22?有替代解决方案吗?
代码:
test = None
for num, line in enumerate(dataFile, 0):
if myString in line:
test = num
try:
test
except:
pass
else:
if (num - test) <= 58:
... do something ...
答案 0 :(得分:2)
遍历您的代码......我将对此进行一些简化:
foo = None
if foo:
print 'Foo is not None' # We never run this
try:
foo # This doesn't do anything, so this segment of the try / except will always end here
except:
print 'The try segment did not raise an error' # We also never get here
else:
print 'Foo is none' # We end up here because Foo is none, so this will print
基本上......您的try / except
子句与if / then
语句无关。这是因为你的缩进。
因此,在您的示例if mystring not in line
中,else
语句中的所有内容都将执行。
您可以更轻松地检查未设置的变量:
if not foo:
# Do something with foo if it doesn't exist
else:
# Continue running your loop since foo was set
答案 1 :(得分:1)
尝试使用if
语句检查test
是否存在NoneType
以外的其他内容。
test = None
for num, line in enumerate(dataFile, 0):
if myString in line:
test = num
if test is not None:
if (num - test) <= 58:
# do something
或者完全摆脱第二个if
声明。
for num, line in enumerate(dataFile, 0):
if (myString in line) and ((num - test) <= 58):
# do something
答案 2 :(得分:1)
首先,在您的代码中,您将不会有异常,因为已创建测试变量。因为你从来没有异常,所以else子句总是会被执行(这就是try / except子句中的else的含义:如果没有引发异常,则运行这部分代码)。
如果您只是想知道变量是否已设置且是否只是继续循环,您可以执行以下操作:
# ...
for num, line in enumerate(dataFile, 0):
# ...
try:
test
except NameError:
# here you say 'skip the rest of loop in case of test was not setted'
continue
# here the rest of the code
在您的情况下,也许更简单的方法是:
for num, line in enumerate(dataFile, 0):
if myString in line:
# in your code, if myString in line, test = num. So, num - test will allways be < 58 when myString in line
# do something