الدرس 5 من 10
الحلقات (Loops)
بدل ما تكتب نفس السطر ألف مرة.
ليه محتاجين Loops؟
عايز تبعت رسالة لألف عميل؟ مش هتكتب print ألف مرة. الـ Loop (الحلقة) بتكرر نفس الكود أكتر من مرة.
for: لما تكون عارف هتكرر كام مرة
# range(1, 6) gives: 1, 2, 3, 4, 5 (stops BEFORE 6) for i in range(1, 6): print(f"7 x {i} = {7 * i}") customers = ["Ali", "Sara", "Omar"] for customer in customers: print(f"Hi {customer}, your order has shipped!")
while: طول ما الشرط لسه متحقق
📱 مثال واقعي: قفل الموبايلعندك ٣ محاولات للباسورد، بعدها الموبايل بيتقفل. انت مش عارف اليوزر هيغلط كام مرة، فبنستخدم
while.correct_pin = "2468" attempts = 0 while attempts < 3: pin = input("Enter PIN: ") if pin == correct_pin: print("Unlocked") break # exit the loop immediately attempts += 1 # same as: attempts = attempts + 1 print(f"Wrong! {3 - attempts} tries left") else: # runs only if the loop ended WITHOUT break print("Phone locked")
break اخرج من الحلقة خالص حالاً.continue سيب اللفة دي وروح على اللي بعدها.+= زوّد على القيمة القديمة.infinite loop حلقة شرطها مبيبقاش False أبداً فبتفضل شغالة للأبد.# Sum only the even numbers from 1 to 10 total = 0 for n in range(1, 11): if n % 2 != 0: continue # skip odd numbers total += n print("Sum of evens:", total)
⚠ الحلقة اللي مبتخلصشلو في
while نسيت تغيّر المتغير اللي في الشرط، هيفضل True للأبد. لو حصل، دوس Ctrl + C في الـ Terminal عشان توقفه.