如果值不存在,则如何设置条件,然后执行一些顺序操作,如果值不存在,则执行其他操作
How to make a condition if the value isn't exist then some sequential actions take place, and if the value isn't exist then other actions take place
我想设置一个条件,如果该值不存在,则执行一些顺序操作,如果该值不存在,则执行其他操作
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中制作这个的源代码?
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:
# indeks_found was not defined
else:
# indeks_found has a value
我想设置一个条件,如果该值不存在,则执行一些顺序操作,如果该值不存在,则执行其他操作
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中制作这个的源代码?
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:
# indeks_found was not defined
else:
# indeks_found has a value