以下是四个功能:
A(),B()和A_B()全部返回预期结果。另一方面,A_B_2()失败,尽管基本相同。
我似乎无法弄清楚为什么尽管与A_B完全相同,A_B_2中的IF AND语句也会被区别对待。
def A(the_filter):
print "start A()"
for o in range(length):
for x in range(length):
if the_filter == "A" and x < 3 :
print the_filter, o, x+1
else:
print the_filter, o, x-x
return "end A()"
def B(the_filter):
print "start B()"
for o in range(length):
for x in range(length):
if the_filter == "B" and o != x :
print the_filter, o, x
else:
print the_filter, "fail"
return "end B()"
def A_B(the_filter):
print "start A_B()"
for o in range(length):
for x in range(length):
if the_filter == "A" :
if x < 3 :
print the_filter, o, x+1
else:
print the_filter, o, x-x
if the_filter == "B" :
if o != x :
print the_filter, o, x
else:
print the_filter, "fail"
return "end A_B()"
def A_B_2(the_filter):
print "start A_B_2()"
for o in range(length):
for x in range(length):
if the_filter == "A" and x < 3 :
print the_filter, o, x+1
else:
print the_filter, o, x-x
if the_filter == "B" and o != x :
print the_filter, o, x
else:
print the_filter, "fail"
return "A_B_2()"
length = 3
print A("A"), "\n"
print B("B"), "\n"
print A_B("A"), "\n"
print A_B("B"), "\n"
print A_B_2("A"), "\n"
print A_B_2("B"), "\n"
我得到的输出是:
start A()
A 0 1
A 0 2
A 0 3
A 1 1
A 1 2
A 1 3
A 2 1
A 2 2
A 2 3
end A()
start B()
B fail
B 0 1
B 0 2
B 1 0
B fail
B 1 2
B 2 0
B 2 1
B fail
end B()
start A_B()
A 0 1
A 0 2
A 0 3
A 1 1
A 1 2
A 1 3
A 2 1
A 2 2
A 2 3
end A_B()
start A_B()
B fail
B 0 1
B 0 2
B 1 0
B fail
B 1 2
B 2 0
B 2 1
B fail
end A_B()
start A_B_2()
A 0 1
A fail
A 0 2
A fail
A 0 3
A fail
A 1 1
A fail
A 1 2
A fail
A 1 3
A fail
A 2 1
A fail
A 2 2
A fail
A 2 3
A fail
A_B_2()
start A_B_2()
B 0 0
B fail
B 0 0
B 0 1
B 0 0
B 0 2
B 1 0
B 1 0
B 1 0
B fail
B 1 0
B 1 2
B 2 0
B 2 0
B 2 0
B 2 1
B 2 0
B fail
A_B_2()
答案 0 :(得分:2)
在您的代码中,Variable
的以下部分:
A_B
不等同于if the_filter == "A" :
if x < 3 :
print the_filter, o, x+1
else:
print the_filter, o, x-x
的以下片段:
A_B_2
即如果if the_filter == "A" and x < 3 :
print the_filter, o, x+1
else:
print the_filter, o, x-x
等于the_filter
,则第一个版本将不执行任何操作(因为"B"
计算为the_filter == "A"
),而第二个版本将执行False
分支(因为else
计算为the_filter == "A" and x < 3
)。
这导致例如出现在由False
打印的第一行(B 0 0
)上,与A_B_2("B")
输出的内容相比较。
答案 1 :(得分:0)
感谢Alex的反馈。 (上图)经过一段时间的睡眠后,我想我已经把头包裹起来,你的回答是有道理的。
为了让A_B_2()返回相同的输出A_B(),我需要用else
替换elif
,以确保在语句的第二部分仍然考虑the_filter
。因此:
def A_B_2(the_filter):
print "start A_B_2()"
for o in range(length):
for x in range(length):
if the_filter == "A" and x < 3 :
print the_filter, o, x+1
elif the_filter == "A" :
print the_filter, o, x-x
if the_filter == "B" and o != x :
print the_filter, o, x
elif the_filter == "B":
print the_filter, "fail"
return "A_B_2()"