Selection — IF and CASE · בחירה — IF וCASE
Making a decision
- Selection means choosing what to do, based on a test.
- An
ifruns its block only when the test is true. - The test gives a Boolean:
TrueorFalse.
קבלת החלטה
- בחירה (Selection) פירונו בחירת פעולה בהתבסס על מבחן.
ifמבצע את הבלוק שלו רק כאשר המבחן נכון.- המבחן מחזיר ערך בוליאני:
TrueאוFalse.
age = 20
if age >= 18:
print("You may vote")
else: the other path
elseruns when theiftest is false.- Exactly one of the two blocks runs.
else: הדרך השנייה
elseמבצע כאשר מבחן הifהוא שגוי.- בדיוק אחד משני הבלוקים ירץ.
mark = 45
if mark >= 50:
print("Pass")
else:
print("Fail")
elif: many paths
- Use
elifto test more conditions in order. - Python checks each test top to bottom and stops at the first true one.
elif: מספר דרכים
- השתמש ב
elifכדי לבדוק תנאים נוספים. - Python בודק כל תנאי מלמעלה למטה ועוצר בהראשון האמיתי.
mark = 72
if mark >= 70:
print("A")
elif mark >= 50:
print("B")
else:
print("C")
if / elif / else — which runs? · if / elif / else — איזה יתבצע?
Tests run top-down; the first true one runs, the rest are skipped. · הבדיקות מתבצעות מלמעלה למטה; הבדיקה האמתית הראשונה מתבצעת, ושאר הבדיקות מודחות.
Comparison operators
==means equal to (the exam writes=).!=means not equal to (the exam writes<>).- Also use
<,>,<=,>=.
מפעילי השוואה
==פירושו שווה ל (במבחן כותבים=).!=פירושו לא שווה ל (במבחן כותבים<>).- ניתן להשתמש גם ב
<,>,<=,>=.
print(5 == 5) # True
print(5 != 3) # True
print(3 <= 2) # False
In the exam: IF and CASE
- Pseudocode uses
IF … THEN … ELSE … ENDIF, orCASEfor many fixed choices.
במבחן: IF ו-CASE
- בפסאודוקוד משתמשים ב
IF … THEN … ELSE … ENDIFאו בCASEעבור בחירות קבועות רבות.
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Common mistakes
- Compare with
==, not=. - Cover every case, including the
else. - Indent the block that belongs to each branch.
טעויות נפוצות
- השווה עם
==, לא עם=. - לכסות את כל המקרים, כולל ה
else. - לתת מקש (הזזה ימינה) לחוסר הקוד השייך לכל ענף.
Now you try
- Read the input, then choose what to print with
if/elif/else. - Press Check answer to test your code.
כעת תנסו בעצמכם
- לקרוא את הקלט, ואז לבחור מה להדפיס באמצעות
if/elif/else. - לחץ על בדוק תשובה כדי לבדוק את הקוד שלך.
Read a whole number, then print even if it divides by 2 with no remainder, otherwise print odd. For input 4, print even. · קרא מספר שלם, והדפס even אם הוא מתחלק ב-2 ללא שארית, אחרת הדפס odd. עבור קלט 4, הדפס even.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Read a mark (0–100). Print A for 70 or more, B for 50–69, and C for anything less. For input 65, print B. · קרא ציון (0–100). הדפס A עבור 70 ומעלה, B עבור 50–69, וC לכל דבר פחות. עבור קלט 65, הדפס B.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Two numbers a and b are set for you. Use an if to store the larger one in biggest. · שני מספרים a וb נקבעו עבורך. השתמש בif כדי לאחסן את הגדול יותר בתוך biggest.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.