Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 22 Online
OpenStudy (anonymous):

Within an if: loop, why do you embed further if:'s within them versus using elif:?

ganeshie8 (ganeshie8):

if <condition> : do this elif <condition> : do that

ganeshie8 (ganeshie8):

elif is exclusive :- either this or that.

ganeshie8 (ganeshie8):

if : if : if: do this

ganeshie8 (ganeshie8):

all conditions have to meet for the nested statement to be executed

OpenStudy (anonymous):

As Gameshie8 said, elif isn't embedding further ifs. Instead, it's giving a range of alternatives. The standard if statement just does something if a condition is met: if money in pocket: buy coffee if/else statements do one of two things, depending on the outcome: if coin=="heads": return "I win" else: return "You lose" if/elif/else statements allow for multiple responses to *the same issue* if fruit=="apple": makeApplePie() elif fruit=="strawberry": makeJam() elif fruit=="raspberry": makePavlova() elif fruit=="orange": makeMarmalade() elif fruit=="banana": makeBananaSplit() else: eatFruit() Here, it's going "if this fruit isn't an apple, see whether it's a strawberry". Embedding ifs can be used as an alternative to using if/and statements: if fruit=="apple": if fruit.breed=="baking": if fruit.ripe==True: if fruit.owner=="You": makeApplePie() else: buy(fruit) makeApplePie() else: waitDays(7) elif fruit.breed=="crabapple": makeJam(fruit) else: if fruit.ripe==True: eat(fruit) else: waitDays(2) could also be: if fruit=="apple" and fruit.breed=="baking" and fruit.ripe==True and fruit.owner=="You": makeApplePie() but this version makes it harder to give appropriate either/or responses to each of the conditions. Basically you'd end up having further if statements lower down anyway to handle non-baking apples, or other people's fruit. You might also use nested if statements in more complicated functions, where ifs don't follow directly from each other: if fruit=="apple": some_value ==True apple_count += 1 thing = someFunction(apple_count) if thing > 4: doSomething() print "text" setAValue(thing) fruit.desirability = getFruitMarket(fruit, apple_count) if fruit.desirability != "High": ignoreFruit() else: buyFruit() return something

OpenStudy (anonymous):

Got it, thanks!

OpenStudy (rsmith6559):

if / elif /else are an or relationship. If this, or elif that, or else the other thing.... If / if / if is an and relationship. If this, and if that, and if the other thing....

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!