I want 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
Local variable indeks_found doesn't exist (or indeks_found doesn't have any value). [I don't know]
In other case, if we change the array to be like this:
first_array = [1, 3, 5, 7, 9]
second_array = [2, 4, 5, 11, 13]
Then, indeks_found is exist (or indeks_found does have a value) [I don't know]
if indeks_found have any value, then do this sequential actions (we call it A) else if indeks_found doesn't have any value, then do this sequential actions (we call it B)
if indeks_found exist, then:
do A
else: indeks_found doesn't exist, then:
do B
So, how to make source code of this in 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')
Also you could simplify the for loop body to:
if first_array[i] == second_array[i]:
found = True
indeks_found = i
break
If you really want to test if a variable has been defined, you can do so by:
try:
indeks_found
except:
# indeks_found was not defined
else:
# indeks_found has a value