如果值不存在,我想设置一个条件,然后执行一些顺序操作,如果值不存在,则执行其他操作
def func():
first_array = [1, 3, 5, 7, 9]
second_array = [2, 4, 6, 8, 10]
found = False
for i in range(len(first_array)):
if first_array[i] == second_array[i]:
found = True
indeks_found = i
if found == True:
break
局部变量 indeks_found 不存在(或 indeks_found 没有任何值)。 [我不知道]
其他情况,如果我们把数组改成这样:
first_array = [1, 3, 5, 7, 9]
second_array = [2, 4, 5, 11, 13]
那么,indeks_found 是存在的(或者 indeks_found 确实有值)[我不知道]
如果 indeks_found 有任何值,则执行此顺序操作(我们称之为 A) 否则如果 indeks_found 没有任何值,则执行此顺序操作(我们称之为 B)
if indeks_found exist, then:
do A
else: indeks_found doesn't exist, then:
do B
那么,如何在python中制作这个源代码?
答案 0 :(得分:2)
def func():
first_array = [1, 3, 5, 7, 9]
second_array = [2, 4, 6, 8, 10]
found = False
indeks_found = None # initialize to none
for i in range(len(first_array)):
if first_array[i] == second_array[i]:
found = True
indeks_found = i
if found == True:
break
if indeks_found == None:
# indeks_found was not changed, i.e nothing found
print('do A')
else:
print('do B')
您也可以将 for 循环体简化为:
if first_array[i] == second_array[i]:
found = True
indeks_found = i
break
如果你真的想测试一个变量是否已经定义,你可以这样做:
try:
indeks_found
except NameError:
# indeks_found was not defined
else:
# indeks_found has a value