תנאיםConditions
if, elif, else, השוואות, and/or/not ואמת/שקר.
if, elif, else, comparisons, and/or/not and truthiness.
01if: לבצע רק אםif: run only when
if בודק תנאי. אם הוא True, הבלוק המוזח שאחריו רץ; אם לא, Python מדלגת עליו. ההזחה (4 רווחים) היא מה שמסמן איפה הבלוק מתחיל ונגמר.
if checks a condition. If it's True, the indented block after it runs; if not, Python skips it. The indentation (4 spaces) marks where the block starts and ends.
pages = int(input("כמה עמודים? "))
if pages > 500:
print("ספר עבה!")
print("כדאי לפנות סופ״ש")
print("בהצלחה בקריאה")pages = int(input("How many pages? "))
if pages > 500:
print("A thick book!")
print("Clear a weekend")
print("Happy reading")כמה עמודים? 640 ספר עבה! כדאי לפנות סופ״ש בהצלחה בקריאה
How many pages? 640 A thick book! Clear a weekend Happy reading
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
if הוא כמו שומר בכניסה למועדון: בודק תנאי (גיל), ורק מי שעומד בו נכנס. השאר ממשיכים הלאה ברחוב.
if is like a bouncer at a club door: checks a condition (age) and only those who pass go in. Everyone else carries on down the street.
שוכחים את הנקודתיים בסוף שורת ה-if.
Forgetting the colon at the end of the if line.
pages = 640
if pages > 500
print("Thick") File "/Users/you/python-course/if_demo.py", line 2
if pages > 500
^
SyntaxError: expected ':'SyntaxError: expected ':': כל if, elif, else נגמרים בנקודתיים.SyntaxError: expected ':': every if, elif, else ends with a colon.תנאי בוחר מה להדפיס לפי הטמפרטורה.
A condition chooses what to print based on the temperature.
temp = 14
if temp > 25:
print("T-shirt")
elif temp > 15:
print("Sweater")
else:
print("Coat")Coat
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02else ו-elif: כמה מסלוליםelse and elif: several paths
else רץ כשהתנאי לא התקיים. elif (קיצור של else if) מוסיף תנאים נוספים. Python בודקת מלמעלה למטה ומריצה את המסלול הראשון שמתאים, ורק אותו.
else runs when the condition didn't hold. elif (short for else if) adds more conditions. Python checks top to bottom and runs the first matching path, and only that one.
score = int(input("ציון: "))
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 60:
print("C")
else:
print("נכשל")score = int(input("Score: "))
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 60:
print("C")
else:
print("Fail")ציון: 84 B
Score: 84 B
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
מה קורה עכשיוWhat happens now
מסך הפלטOutput screen
elif הוא כמו מכונת מיון מטבעות: המטבע נופל דרך חורים מהגדול לקטן, ונעצר בחור הראשון שהוא נכנס אליו.
elif is like a coin sorter: the coin drops past holes from largest to smallest and stops at the first one it fits.
כותבים else עם תנאי.
Writing a condition after else.
x = 5
if x > 10:
print("big")
else x > 3:
print("medium") File "/Users/you/python-course/grade.py", line 4
else x > 3:
^
SyntaxError: expected ':'SyntaxError: ל-else אין תנאי. תנאי נוסף כותבים עם elif.SyntaxError: else takes no condition. Another condition uses elif.03השוואותComparisons
אופרטורי השוואה מחזירים True או False. הכי חשוב: = (השמה) שונה מ-== (שאלה: האם שווים?). אפשר גם להשוות מחרוזות: "apple" < "banana" לפי סדר מילוני.
Comparison operators return True or False. Most important: = (assignment) is not == (asking: are they equal?). Strings compare too: "apple" < "banana" in dictionary order.
age = 16
print(age == 16, age != 16)
print(13 <= age < 18)
print("apple" < "banana")
print("Zebra" < "apple")True False True True True
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
= הוא "שים את זה בקופסה". == הוא "האם מה שבקופסה זהה לזה?". פעולה מול שאלה.
= is "put this in the box". == is "is what's in the box the same as this?". An action versus a question.
אותיות גדולות באות לפני קטנות בהשוואת מחרוזות. להשוואה בלי רגישות: a.lower() == b.lower().
Uppercase letters sort before lowercase. For a case-insensitive comparison: a.lower() == b.lower().
משתמשים ב-= בתוך תנאי.
Using = inside a condition.
age = 16
if age = 16:
print("16!") File "/Users/you/python-course/compare.py", line 2
if age = 16:
^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?SyntaxError: Python אפילו שואלת אם התכוונתם ל-==. בתנאי משווים עם ==.SyntaxError: Python even asks whether you meant ==. Conditions compare with ==.04and, or, notand, or, not
אופרטורים לוגיים מחברים תנאים. and נכון רק אם שני הצדדים נכונים, or אם לפחות אחד, ו-not הופך True ל-False ולהפך.
Logical operators combine conditions. and is true only if both sides are, or if at least one is, and not flips True and False.
age = 15
has_ticket = True
with_parent = False
if has_ticket and (age >= 16 or with_parent):
print("נכנסים")
else:
print("מצטערים")
print(not has_ticket)age = 15
has_ticket = True
with_parent = False
if has_ticket and (age >= 16 or with_parent):
print("Come in")
else:
print("Sorry")
print(not has_ticket)מצטערים False
Sorry False
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
| A | B | A and B | A or B |
|---|---|---|---|
| True | True | True | True |
| True | False | False | True |
| False | True | False | True |
| False | False | False | False |
and הוא כמו כספת עם שני מפתחות: צריך את שניהם. or הוא כמו בית עם שתי דלתות: מספיקה אחת.
and is like a safe with two keys: you need both. or is like a house with two doors: one is enough.
כותבים x == 1 or 2 במקום שני תנאים מלאים. זה לא נופל, אבל תמיד True!
Writing x == 1 or 2 instead of two full conditions. It doesn't crash, but it's always True!
x = 5
if x == 1 or x = 2:
print("one or two") File "/Users/you/python-course/logic.py", line 2
if x == 1 or x = 2:
^
SyntaxError: invalid syntaxSyntaxError: כל צד צריך תנאי שלם עם ==: x == 1 or x == 2, או x in (1, 2).SyntaxError: each side needs a full condition with ==: x == 1 or x == 2, or x in (1, 2).and דורש ששני הדברים יהיו נכונים, or מסתפק באחד.
and needs both things true; or is happy with one.
homework_done = True
hour = 18
weekend = False
if homework_done and hour < 20:
print("Play time!")
if weekend or hour < 8:
print("Sleep in")
else:
print("Up early")Play time! Up early
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05truthy ו-falsyTruthy and falsy
בתנאי לא חייבים True/False מפורשים. ערכים "ריקים" (0, "", None, רשימה ריקה) נחשבים falsy, וכל השאר truthy. ככה בודקים בקצרה אם המשתמש הקליד משהו.
A condition doesn't need an explicit True/False. "Empty" values (0, "", None, an empty list) are falsy, everything else truthy. That's the short way to check whether the user typed something.
name = input("שם (אפשר ריק): ")
if name:
print(f"שלום {name}")
else:
print("שלום, אורח/ת")name = input("Name (can be empty): ")
if name:
print(f"Hi {name}")
else:
print("Hi, guest")שם (אפשר ריק): שלום, אורח/ת
Name (can be empty): Hi, guest
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו לבדוק אם יש משהו בארנק: לא צריך לספור כמה, רק אם הוא ריק או לא.
It's like checking whether there's anything in your wallet: you don't count, you just check if it's empty.
משווים מחרוזת מהקלט למספר.
Comparing a string from input with a number.
age = input("Age? ")
if age >= 18:
print("adult")Age? 20
Traceback (most recent call last):
File "/Users/you/python-course/truthy.py", line 2, in <module>
if age >= 18:
^^^^^^^^^
TypeError: '>=' not supported between instances of 'str' and 'int'TypeError: '>=' not supported between instances of 'str' and 'int': ממירים עם int(input(...)).TypeError: '>=' not supported between instances of 'str' and 'int': convert with int(input(...)).צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06קינון והזחהNesting and indentation
אפשר לשים if בתוך if, וכל רמה מוזחת עוד 4 רווחים. הזחה היא חלק מהתחביר: היא קובעת לאיזה בלוק שייכת כל שורה. כשהקינון עמוק, כדאי לחבר תנאים עם and.
You can put an if inside an if, each level indented 4 more spaces. Indentation is part of the syntax: it decides which block each line belongs to. When nesting gets deep, combine conditions with and.
member = True
books = 3
if member:
if books < 5:
print("אפשר לשאול עוד ספר")
else:
print("הגעת למקסימום")
else:
print("צריך להירשם")member = True
books = 3
if member:
if books < 5:
print("You can borrow another")
else:
print("You reached the limit")
else:
print("Please sign up")אפשר לשאול עוד ספר
You can borrow another
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הזחה היא כמו תיקיות בתוך תיקיות: מה שבפנים שייך לתיקייה שעוטפת אותו.
Indentation is like folders inside folders: whatever is inside belongs to the folder around it.
שוכחים להזיח את הבלוק.
Forgetting to indent the block.
pages = 600
if pages > 500:
print("thick") File "/Users/you/python-course/nested.py", line 3
print("thick")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 2IndentationError: expected an indented block: מזיחים 4 רווחים (או Tab ב-VS Code).IndentationError: expected an indented block: indent 4 spaces (or Tab in VS Code).סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.