0
how to use multiple if-statements instead of nested if
4 odpowiedzi
+ 4
Let's imagine we've got an AI testing a picture for certain attributes (like color, objects, etc). Here's a nested "if":
if blue_in_picture:
if feathers_in_picture:
its_a_parrot = True
else:
if hair_in_picture:
if hair_is_blue:
its_grandma = True
else:
print("Found no blue clues")
Note that I could write at least one of those with elif (which is still nesting "if's"):
if blue_in_picture:
if feathers_in_picture:
its_a_parrot = True
elif hair_in_picture:
if hair_is_blue:
its_grandma = True
else:
print("Found no blue clues")
Nesting "if's" (where elif is just more nesting) brings forward 'what we already know' and makes the tests more specific. To write the same thing with multiple "if" statements, you have to determine and recreate the entire context for every test:
if feathers_in_picture and blue_in_picture:
its_a_parrot = True
if !feathers_in_picture and blue_in_picture and hair_in_picture and hair_is_blue:
its_grandma = True
if !blue_in_picture:
print("Found no blue clues")
The second "if" must include the ! to replace "elif" and the blue_in_picture - because you've lost both of those contexts at the end of the last test.
The third "if" doesn't need any of that context but now maybe you should rearrange the first two if's so it's clear what you're testing first, which hides the "!" on the next parameter.
For nested tests the separation is probably less clear, may be mistake-prone and at least wastes CPU cycles retesting the same thing repeatedly.
By the way, this is a terrible series of tests - I'm not trying to make an airtight scenario (this isn't even close); it's just an example.
+ 1
Question's slightly broad. Do you have an example what to break apart? Should it have else/elif? Or just a general comparison is OK?
Edit: I'll return to write a comparison; the problem you're probably solving is that "nested if's" carry context through, whereas multiple if statements often have to repeat contexts.
0
if:
elif:
elif:
elif:
....
else:
0
An easy question