我遇到了一个问题。。。否则。。。我正在测试是否使用try
设置了一个变量。如果没有设置,我只想继续循环。如果已经设置了变量,我想运行else
部分。然而,Python抛出了一个抖动,因为它试图在else
部分执行操作,而失败是因为变量尚未设置。有点像第二十二条军规?有别的解决办法吗?你知道吗
代码:
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 ...
尝试使用
if
语句来检查test
是否作为NoneType
以外的内容存在。你知道吗或者完全摆脱第二个
if
语句。你知道吗首先,在代码中不会出现异常,因为测试变量是创建的。由于从来没有异常,因此始终会执行else子句(这就是try/except子句中的else的含义:如果这里没有引发异常,则运行这部分代码)。你知道吗
如果你只是想知道一个变量是否被设置了,如果它不只是继续循环,你可以这样做:
在你的情况下,也许更简单的方法是:
浏览你的代码。。。我将把它简化为:
基本上。。。您的
try / except
子句与if / then
语句没有关联。这是因为你的压痕。你知道吗因此在您的示例
if mystring not in line
中,else
语句中的所有内容都将执行。你知道吗您可以更轻松地检查未按以下方式设置的变量:
相关问题 更多 >
编程相关推荐