Overall Course Progress التقدم الإجمالي في الدورة 0%
0 of 15 Days Completed تم إكمال 0 من 15 يوماً Target: 1 Hour/Day المستهدف: ساعة/يوم
Day 5 اليوم 5

Complex Conditionals and Puzzles الشروط المركبة وحل الألغاز المنطقية

Practical عملي 1 Hour 1 ساعة

Learning Outcomes مخرجات التعلم

  • Utilize 'elif' chains to handle multiple independent conditions.
  • Combine conditions using logical operators (and, or, not).
  • Design nested conditional statements for complex decision-making.
  • Solve a logic puzzle by translating human rules into conditional code.
  • استخدام جمل 'elif' المتتابعة للتعامل مع شروط متعددة ومستقلة.
  • دمج الشروط المختلفة معاً باستخدام المعاملات المنطقية (and، or، not).
  • تصميم جمل شرطية متداخلة (Nested) لاتخاذ القرارات الهرمية المعقدة.
  • حل لغز منطقي عن طريق تحويل قواعد لغوية إلى أكواد شرطية.

1. Cascading Conditions with Elif

When you have more than two possible mutually exclusive outcomes, a simple if-else structure is not enough. Python provides the elif (short for "else if") statement to cascade multiple conditions. Python evaluates these conditions from top to bottom. The moment it finds a condition that is True, it executes its block and skips the rest of the entire cascade.

# Checking multiple grades
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B") # Only runs if score >= 90 was False AND score >= 80 is True
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F") # Runs only if all above are False
Elif Chain Cascade
Figure 5.1: Flowchart illustrating the cascading nature of an elif chain, checking checks sequentially until a True value is hit.
Complex Conditionals Glossary
Elif Cascade: A chain of sequential condition checks where only the first matching True block executes.
Logical Operator: Operators used to combine or negate multiple boolean expressions (and, or, not).

2. Combining Conditions with Logical Operators

We can combine multiple checks in a single if statement using logical operators:

  • and: Returns True only if **both** conditions are true (e.g. x > 0 and x < 10).
  • or: Returns True if **at least one** condition is true (e.g. has_ticket or is_admin).
  • not: Inverts the boolean value (e.g. not is_valid returns True if is_valid is False).
Logical Operators Truth Mechanics
Figure 5.2: Logical operators breakdown illustrating how and, or, and not evaluate truth inputs.

3. Nested Conditionals

You can place an if statement inside another if statement. This is called **nesting**. It is useful for hierarchies of decisions, where an inner check is only relevant if the outer check has succeeded.

is_weekend = True
temp = 32
if is_weekend:
    if temp > 30:
        print("Go to the beach!") # Nested conditional branch
    else:
        print("Relax at home.")
else:
    print("Go to work.")
Nested Conditionals Decision Tree
Figure 5.3: Visualizing nested conditionals as a decision tree where inner choices depend entirely on outer condition branches.
⚠️

Nesting Overhead: Nesting too deep (e.g. 4 or 5 levels of indented if statements) makes your code very hard to read and debug. Try to combine conditions using and or use elif structures where possible to flatten the hierarchy.

4. Resolving Cascading Path Bugs

The order of checks in an elif chain is critical. Putting broader checks before specific checks can shadow and disable the specific checks completely.

Incorrect Code (Shadowed Conditions):
# General condition placed before specific
score = 95
if score >= 70:
    print("Pass") # Runs first and exits!
elif score >= 90:
    print("Excellent") # Never reached!
Correct Code (Specific to General):
score = 95
if score >= 90:
    print("Excellent") # Specific first
elif score >= 70:
    print("Pass") # General second

1. الشروط المتتالية باستخدام Elif

عندما يكون لديك أكثر من احتمالين متبادلين، لا تكفي بنية if-else البسيطة. توفر بايثون جملة elif (اختصار لـ "else if") لربط شروط متعددة متتالية. تقيم بايثون هذه الشروط من الأعلى إلى الأسفل. وبمجرد العثور على أول شرط قيمته True، فإنها تنفذ كتلتها وتتخطى بقية السلسلة بالكامل.

# فحص درجات متعددة
score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B") # ينفذ فقط إذا كان الشرط الأول False والثاني True
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F") # ينفذ إذا كانت جميع الشروط السابقة False
سلسلة شروط elif
الشكل 5.1: مخطط تدفق يوضح الطبيعة التتابعية لسلسلة شروط elif، حيث يتم التحقق من الشروط بالتوالي حتى العثور على القيمة الصحيحة.
قاموس الشروط المركبة
سلسلة Elif (Elif Cascade): سلسلة من عمليات الفحص الشرطي المتتالية حيث يتم تنفيذ كتلة الكود التابعة لأول شرط صحيح فقط.
المعامل المنطقي (Logical Operator): معاملات تُستخدم لربط أو عكس التعبيرات المنطقية (and، or، not).

2. دمج الشروط باستخدام المعاملات المنطقية

يمكننا دمج فحوصات متعددة في جملة if واحدة باستخدام المعاملات المنطقية:

  • and: يعيد True فقط إذا كان **كلا** الشرطين صحيحين (مثال: x > 0 and x < 10).
  • or: يعيد True إذا كان **أحد** الشرطين على الأقل صحيحاً (مثال: has_ticket or is_admin).
  • not: يعكس القيمة المنطقية (مثال: not is_valid تعيد True إذا كانت القيمة الأصلية False).
مخطط منطق البوابات
الشكل 5.2: تحليل طريقة عمل المعاملات المنطقية وكيفية تقييمها للمدخلات المنطقية.

3. الجمل الشرطية المتداخلة (Nested Conditionals)

يمكنك كتابة جملة if داخل جملة if أخرى. يسمى هذا بالـ **تداخل**. وهو مفيد في القرارات الهرمية، حيث لا يكون للفحص الداخلي أي أهمية إلا إذا نجح الفحص الخارجي أولاً.

is_weekend = True
temp = 32
if is_weekend:
    if temp > 30:
        print("Go to the beach!") # شرط متداخل داخلي
    else:
        print("Relax at home.")
else:
    print("Go to work.")
شجرة القرارات للشروط المتداخلة
الشكل 5.3: تمثيل الشروط المتداخلة كشجرة قرارات تعتمد فيها الخيارات الداخلية كلياً على فروع الشروط الخارجية.
⚠️

تجنب التداخل العميق: يؤدي التداخل العميق (مثل 4 أو 5 مستويات) لجعل الكود صعب القراءة ومربكاً في التتبع. حاول دمج الشروط بـ and أو استخدام شروط elif لتبسيط الكود وتسطيحه.

4. ترتيب الشروط المتتالية لتفادي الأخطاء المنطقية

ترتيب الشروط في سلسلة elif مهم جداً. وضع الشروط العامة والواسعة قبل الشروط الخاصة والضيقة يمكن أن يحجب الشروط الخاصة ويمنع تنفيذها تماماً.

كود خاطئ (شروط محجوبة):
# وضع الشرط العام أولاً
score = 95
if score >= 70:
    print("Pass") # ينفذ هذا الشرط أولاً ويخرج مباشرة!
elif score >= 90:
    print("Excellent") # لا يمكن الوصول لهذا السطر أبداً!
كود صحيح (الخاص أولاً):
score = 95
if score >= 90:
    print("Excellent") # الشرط الخاص والأكثر دقة أولاً
elif score >= 70:
    print("Pass") # الشرط العام ثانياً
Practical Activity النشاط العملي

Treasure Island Gatekeeper حارس بوابة جزيرة الكنز

Solve this logic puzzle by writing a program that directs a player at a temple entrance:

  1. Create variables has_key (boolean) and knows_password (boolean). Set them dynamically.
  2. Ask the user to enter their energy_level (integer, 0 to 100).
  3. Write conditional checks:
    • If the player has the key **and** knows the password, they can open the "Golden Gate".
    • If they don't have the key but know the password **and** their energy level is above 80, they can open the "Silver Gate" by pushing it.
    • Otherwise, they are "Denied Entry".

قم بحل هذا اللغز المنطقي بكتابة برنامج يوجه اللاعب عند مدخل المعبد الأثري:

  1. أنشئ متغيرات منطقية (Boolean): has_key (يمتلك المفتاح) و knows_password (يعرف كلمة المرور).
  2. اطلب من المستخدم إدخال مستوى طاقته energy_level كعدد صحيح بين 0 و 100.
  3. اكتب الجمل الشرطية التالية:
    • إذا كان اللاعب يملك المفتاح **و** يعرف كلمة المرور، يطبع البرنامج "تم فتح البوابة الذهبية بنجاح".
    • إذا كان اللاعب لا يملك المفتاح ولكنه يعرف كلمة المرور **و** مستوى طاقته أكبر من 80، يطبع البرنامج "تم دفع وفتح البوابة الفضية".
    • خلاف ذلك، يطبع البرنامج "تم رفض الدخول".
Model Answer (Python Code)
الإجابة النموذجية (كود بايثون)
# Step 1: Initialize game state variables
has_key = False
knows_password = True

# Step 2: Capture numerical energy level
energy_input = input("Enter your energy level (0-100): ")

if energy_input.isdigit():
    energy = int(energy_input)
    
    # Step 3: Combined and complex logic checks
    if has_key and knows_password:
        print("Success: You opened the Golden Gate!")
    elif (not has_key) and knows_password and energy > 80:
        print("Success: You pushed open the Silver Gate!")
    else:
        print("Access Denied: You do not meet the gate requirements.")
else:
    print("Error: Energy level must be a numeric integer!")

Run the code above in your Thonny or VS Code IDE. Inspect variable outputs and logic flow to ensure it behaves exactly as described. قم بتشغيل الكود أعلاه في بيئة Thonny أو VS Code. تتبع مخرجات المتغيرات ومسار المنطق للتأكد من عمل الكود بالشكل الصحيح.