إنهاء الحلقات مبكراً باستخدام break
تمرين: اكتب برنامجًا يستقبل قائمة وقيمة، ثم يتحقق مما إذا كانت القائمة تحتوي على هذه القيمة. مثلًا، إذا كانت القيم:
things = ['This', 'is', 'a', 'list']
thing_to_find = 'is'
فيجب أن يطبع True. أما إذا كانت:
thing_to_find = 'other'
فيجب أن يطبع False.
You will need a loop.
You will need an
ifstatement.You will need a comparison operator.
Specifically
==.You need a boolean variable that you print at the end.
If you find the element in the list you should set that variable to
True.Once you've found the element, you can't unfind it.
That means that once you set the variable to
True, it should never be set to anything else after that.Don't use an
else.There is no reason to ever set the variable to
Falseinside the loop.
جيد جدًا!
حل نموذجي قد يبدو هكذا:
found = False for thing in things: if thing == thing_to_find: found = True
print(found)
غالبًا سيكون حلك قريبًا من ذلك. هذا الحل صحيح، لكنه ينفذ الحلقة على القائمة كلها حتى لو وجد العنصر في بدايتها. تستطيع إيقاف أي حلقة فورًا باستخدام break:
for thing in things: if thing == thing_to_find: found = True break النسخة الثانية صحيحة أيضًا، لكنها تتجنب دورات واختبارات لا حاجة لها بعد العثور على العنصر. يمكنك استخدام متتبع التنفيذ لرؤية الفرق بين النسختين خطوة بخطوة.