كل شرط تكتبه بعد if له في النهاية قيمة واحدة من اثنتين: True (صحيح) أو False (خطأ). جرّب طباعة مقارنة مباشرة:
print(5 > 3) print(10 == 7) score = 80 print(score >= 75)
True False True
هاتان القيمتان نوع بيانات اسمه bool (النوع المنطقي). تُكتبان بدون علامتي تنصيص، وبحرف كبير في أولهما. ونعرف نوع أي قيمة بـ type():
is_sunny = "True" print(type(is_sunny)) is_sunny = True print(type(is_sunny))
<class 'str'> <class 'bool'>
"True" بين علامتي تنصيص نص (str)، أما True بدونهما فهي bool. وكتابة true بحرف صغير تسبب خطأ.متغير bool داخل if
جملة if تنفّذ ما تحتها عندما تكون قيمة الشرط True. لذلك يمكن أن نكتب متغير bool وحده كشرط، بدل is_sunny == True:
is_sunny = False
if is_sunny:
print("Practice on the field")
else:
print("Practice in the gym")Practice in the gym
حفظ نتيجة شرط
يمكن أن نفحص شرطًا ونحفظ نتيجته في متغير، ثم نستخدم هذا المتغير مع شرط آخر. القيمة None تعني «لا قيمة بعد»، ونبدأ بها المتغير:
stamp_count = 8
help_count = 5
quiz_score = 80
result = None
if stamp_count >= 8 and help_count >= 4:
result = True
else:
result = False
if result and quiz_score >= 75:
print("Booth approved!")
else:
print("Maybe next year!")Booth approved!
وبما أن المقارنة نفسها تعطي True أو False، يمكن إسنادها إلى المتغير مباشرة في سطر واحد:
age = 17 is_adult = age >= 18 print(is_adult)
False
تدريبات
أسند True إلى is_sunny ليُطبع Practice on the field.
is_sunny = ___
if is_sunny:
print("Practice on the field")
else:
print("Practice in the gym")اضغط «تشغيل» لترى النتيجة. أكمل الشرط ليُطبع Ready to go! إذا كانت قيمة is_ready صحيحة. اكتب المتغير وحده كشرط.
is_ready = True
___
print("Ready to go!")
else:
print("Not ready yet...")اضغط «تشغيل» لترى النتيجة. اطبع نوع البيانات للقيمة المُسندة إلى is_sunny باستخدام type().
is_sunny = True
اضغط «تشغيل» لترى النتيجة. إذا تحقق الشرط أسند True إلى result، وإلا أسند False.
ticket_count = 8
help_count = 5
result = False
if ticket_count >= 8 and help_count >= 4:
___
else:
___
if result:
print("Booth approved!")
else:
print("Maybe next year!")اضغط «تشغيل» لترى النتيجة. أكمل الشرط الثاني: result صحيحة و quiz_score تساوي 75 أو أكثر.
stamp_count = 8
help_count = 5
quiz_score = 60
result = None
if stamp_count >= 8 and help_count >= 4:
result = True
else:
result = False
if ___:
print("Booth approved!")
else:
print("Maybe next year!")اضغط «تشغيل» لترى النتيجة. البرنامج يطبع دائمًا Bring your umbrella مع أن المطر غير متوقع. السبب أن القيمة نص وليست bool. صحّحه ليطبع No umbrella needed.
تلميح
أي نص غير فارغ يُعامل كأنه True داخل if.will_rain = "False"
if will_rain:
print("Bring your umbrella")
else:
print("No umbrella needed")اضغط «تشغيل» لترى النتيجة. لدينا homework_done = True و mark = 64. أسند إلى passed نتيجة المقارنة mark >= 50. إذا كان الواجب منتهيًا و passed صحيحة اطبع You can play now، وإلا اطبع Study first.
homework_done = True mark = 64
اضغط «تشغيل» لترى النتيجة. النقاط الرئيسية
- النوع bool قيمته
TrueأوFalseفقط، بدون علامتي تنصيص. - المقارنة مثل
score >= 75تعطي قيمة bool، ويمكن حفظها في متغير. if is_sunny:تعني نفسif is_sunny == True:.