Python "if" statement ignored
Question:
I’m triggering loop within loop in Python, if one of the multiple conditions ("or") is met.
The script seems to skip the "if" statement and enters inner loop without meeting required conditions.
Code
# Begin TestCase
# Main logic: execute RemoteController macro, if expected state == true, set 'Success', else: Fail
for macroname_n in range (32):
handler("RemoteController", "SET", "[{0}_{1}_{2}]".format(testcase, macroname_n, platform), "")
result = pbc_json(disk, testcase_area, testcase, platform, filename_n, coord_n)
filename_n += 1
coord_n += 1
if macroname_n == 15 or 20:
success_counter = 0
for extra_loop in range(15):
handler("RemoteController", "SET", ""down 4"", "")
result = pbc_json(disk, testcase_area, testcase, platform, filename_n, coord_n)
filename_n += 1
if result >= 50:
success_counter += 1
if success_counter <> 15:
result = 0
Thanks in advance!
Answers:
20
always evaluates to true
in a boolean context. Therefore, macroname_n == 15 or 20
is always true
.
You probably want to write:
if macroname_n == 15 or macroname_n == 20:
success_counter = 0
# ...
This line does not do what you want:
if macroname_n == 15 or 20:
This is parsed as follows:
if (macroname_n == 15) or (20):
Since 20
is always true in a boolean context, the statement is always true. What you actually want is this:
if macroname_n in (15, 20):
if macroname_n == 15 or 20:
should be:
if macroname_n == 15 or macroname_n == 20:
otherwise will it always read 20 as true.
I’m triggering loop within loop in Python, if one of the multiple conditions ("or") is met.
The script seems to skip the "if" statement and enters inner loop without meeting required conditions.
Code
# Begin TestCase
# Main logic: execute RemoteController macro, if expected state == true, set 'Success', else: Fail
for macroname_n in range (32):
handler("RemoteController", "SET", "[{0}_{1}_{2}]".format(testcase, macroname_n, platform), "")
result = pbc_json(disk, testcase_area, testcase, platform, filename_n, coord_n)
filename_n += 1
coord_n += 1
if macroname_n == 15 or 20:
success_counter = 0
for extra_loop in range(15):
handler("RemoteController", "SET", ""down 4"", "")
result = pbc_json(disk, testcase_area, testcase, platform, filename_n, coord_n)
filename_n += 1
if result >= 50:
success_counter += 1
if success_counter <> 15:
result = 0
Thanks in advance!
20
always evaluates to true
in a boolean context. Therefore, macroname_n == 15 or 20
is always true
.
You probably want to write:
if macroname_n == 15 or macroname_n == 20:
success_counter = 0
# ...
This line does not do what you want:
if macroname_n == 15 or 20:
This is parsed as follows:
if (macroname_n == 15) or (20):
Since 20
is always true in a boolean context, the statement is always true. What you actually want is this:
if macroname_n in (15, 20):
if macroname_n == 15 or 20:
should be:
if macroname_n == 15 or macroname_n == 20:
otherwise will it always read 20 as true.