[Tutor] Flow control question.
Jeff Shannon
jeff at ccvcorp.com
Mon Aug 11 12:34:35 EDT 2003
Clay Shirky wrote:
>On these errors, I return with 0, then, in the "check addresses" loop, I try
>to 'continue' if the return value is 0, but it isn't working.
>
[...]
>for new_address in new_addresses:
> if new_address == 0: continue # I want to skip the next test
> if test_mac(new_address) == test_mac(orig_address):
> print new_address, "matches", orig_address
> else:
> print new_address, "doesn't match..."
>
I'm not entirely certain what you're after, here. Your description
doesn't seem to match the code, and I'm not sure whether the confusion
is yours or mine. ;) Anyhow, as best as I can tell...
Your first if statement, above
if new_address == 0: continue # I want to skip the next test
Simply tests to see if the address that was fed in is equal to zero.
Now, at this point, you haven't run test_mac() on it; you're simply
looking to see if the potential MAC address is equal to zero. I'd
expect that your potential address should be a string, and thus will
never be equal to zero, so I'm not sure what the intent here is. Did
you mean to compare the result of test_mac(new_address), perhaps?
At any rate, there's a couple of ways to skip the second if statement
depending on what happens here. Probably the simplest is to move the
second test a level in -- put it in the else clause of the first if
statement. Actually, since you're not doing anything if the first test
is true, then you can just reverse the sense of that test and have that
test control the second one --
if new_address != 0: # Not equal, instead of equal, no continue
if test_mac(new_address) == test_mac(orig_address):
print new_address, "matches", orig_address
else:
print new_address, "doesn't match..."
As a minor point, consider that, if new_address is indeed equal to zero,
it evaluates to a boolean false all by itself, and if it's *not* equal
to zero (or the empty string, or the empty list, or None), then it
evaluates to true all by itself. Thus, the line
if new_address != 0:
is in practice equivalent to
if new_address:
and that second form is the preferred one. (Note, also, that all of
this applies regardless of whether the intent was to test new_address
itself, or the result of test_mac(new_address) -- it's the same
principle either way.)
If you *did* intend for the first test to be against the result of
test_mac(), then you might be better off running that function only once
and saving the result --
for new_address in new_addresses:
result = test_mac(new_address)
if result:
if result == test_mac(orig_address):
print new_address, "matches", orig_address
else:
print new_address, "doesn't match..."
This avoids the duplicate effort of running test_mac(new_address) twice.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list