Complex Conditionals and Puzzles الشروط المركبة وحل الألغاز المنطقية
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
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: ReturnsTrueonly if **both** conditions are true (e.g.x > 0 and x < 10).or: ReturnsTrueif **at least one** condition is true (e.g.has_ticket or is_admin).not: Inverts the boolean value (e.g.not is_validreturnsTrueifis_validisFalse).
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.")
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.
# General condition placed before specific
score = 95
if score >= 70:
print("Pass") # Runs first and exits!
elif score >= 90:
print("Excellent") # Never reached!
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
المعامل المنطقي (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).
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.")
تجنب التداخل العميق: يؤدي التداخل العميق (مثل 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") # الشرط العام ثانياً
Treasure Island Gatekeeper حارس بوابة جزيرة الكنز
Solve this logic puzzle by writing a program that directs a player at a temple entrance:
- Create variables
has_key(boolean) andknows_password(boolean). Set them dynamically. - Ask the user to enter their
energy_level(integer, 0 to 100). - 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".
قم بحل هذا اللغز المنطقي بكتابة برنامج يوجه اللاعب عند مدخل المعبد الأثري:
- أنشئ متغيرات منطقية (Boolean):
has_key(يمتلك المفتاح) وknows_password(يعرف كلمة المرور). - اطلب من المستخدم إدخال مستوى طاقته
energy_levelكعدد صحيح بين 0 و 100. - اكتب الجمل الشرطية التالية:
- إذا كان اللاعب يملك المفتاح **و** يعرف كلمة المرور، يطبع البرنامج "تم فتح البوابة الذهبية بنجاح".
- إذا كان اللاعب لا يملك المفتاح ولكنه يعرف كلمة المرور **و** مستوى طاقته أكبر من 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. تتبع مخرجات المتغيرات ومسار المنطق للتأكد من عمل الكود بالشكل الصحيح.