The if-elif-else chain is powerful, but it’s only appropriate to use when
you just need one test to pass. As soon as Python finds one test that
passes, it skips the rest of the tests. This behavior is beneficial, because
it’s efficient and allows you to test for one specific condition.
However, sometimes it’s important to check all of the conditions of
interest. In this case, you should use a series of simple if statements with
no elif or else blocks. This technique makes sense when more than one
condition could be True, and you want to act on every condition that is
True.
Let’s reconsider the pizzeria example. If someone requests a twotopping pizza, you’ll need to be sure to include both toppings on their
pizza.
سلسلة if-elif-else قوية، لكنها مناسبة فقط عندما تحتاج لاختبار واحد للنجاح. بمجرد أن يجد بايثون اختباراً واحداً ينجح، فإنه يتخطى بقية الاختبارات. هذا السلوك مفيد لأنه كفء ويسمح لك باختبار حالة معينة فقط.
ومع ذلك، في بعض الأحيان يكون من المهم التحقق من جميع الشروط المهمة. في هذه الحالة، يجب عليك استخدام سلسلة من جمل if البسيطة بدون كتل elif أو else. هذه التقنية منطقية عندما يمكن أن تكون أكثر من حالة واحدة صحيحة، وتريد تنفيذ الإجراء لكل حالة صحيحة.
دعنا نعيد النظر في مثال البيتزا. إذا طلب شخص ما بيتزا بغطائين، ستحتاج إلى التأكد من تضمين كلا الغطائين في البيتزا الخاصة بهم: