[英]if variable is assigned then check some condition in python
I am coding in python.我正在用python编码。 My problem is I have a variable
strGUID
in the function and then there is an if control flow in which I want to check if the variable is assigned and if yes then check on some condition on it.我的问题是我在函数中有一个变量
strGUID
,然后有一个 if 控制流,我想在其中检查变量是否已分配,如果是,则检查它的某些条件。 Clarifying piece of code is follows :澄清一段代码如下:
for line in data_list:
if line.find('Project')!=-1
strGUID = line.split(',')[2].strip('" ')
if flag == False and line.find(strGUID)==-1 :
print 'wrote line : ', line
In the above code I get an error sometimes saying在上面的代码中,我有时会收到一个错误说
that the variable strGUID is accesses before its assignment.
变量 strGUID 在赋值之前被访问。
so what I want to do is to check in the second if loop if the variable strGUID is defined and if it is then check for condition : line.find(strGUID)==-1
.所以我想要做的是检查第二个 if 循环是否定义了变量 strGUID ,如果它是然后检查条件:
line.find(strGUID)==-1
。 Something like就像是
if flag == False and (if strGUID then line.find(strGUID)==-1) :
PS : this is just to shorten the code and make it intelligent, I know that I can write longer lengthier if checks in the code, so asking for that is not the purpose. PS:这只是为了缩短代码并使其智能,我知道如果检查代码我可以写更长的时间,所以要求这不是目的。
clarification : In case if you want to suggest the answer where you initialli assign strGUID = None and then check it in the second if loop, I want to execute print even when the strGUID is None.澄清:如果你想建议你初始分配 strGUID = None 的答案,然后在第二个 if 循环中检查它,我想即使 strGUID 为 None 也执行打印。 Hence I am searching for an intelligent way of defining if condition.
因此,我正在寻找一种定义 if 条件的智能方法。 ie I want print to get executed if strGUID = None or if strGUID is not None and line.find(strGUID)==-1
即如果 strGUID = None 或者如果 strGUID 不是 None 和 line.find(strGUID)==-1,我希望打印被执行
edit : basically my current code has second if loop as :编辑:基本上我当前的代码有第二个 if 循环:
if flag == False and (strGUID is None or (strGUID is not None and line.find(strGUID)==-1) ) :
I want to check if there is an intelligent way to shorten it.我想检查是否有一种聪明的方法来缩短它。
The customary way to do this would be to set strGUID = None
at the start, and then check这样做的习惯方法是在开始时设置
strGUID = None
,然后检查
if flag == False and (strGUID is not None and line.find(strGUID) == -1):
If the first part ( strGUID is not None
) is false, the second part ( line.find(strGUID) == -1
) will never be evaluated.如果第一部分(
strGUID is not None
)为假,则永远不会评估第二部分( line.find(strGUID) == -1
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.