נבנה על ידיBuilt by Ariel Yohimovich

PythonPython
5
חלקPart 1: יסודותFoundations כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

תנאים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.

if_demo.py
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")
פלטOutput
כמה עמודים? 640
ספר עבה!
כדאי לפנות סופ״ש
בהצלחה בקריאה
How many pages? 640
A thick book!
Clear a weekend
Happy reading
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

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.

טעות נפוצהCommon mistake

שוכחים את הנקודתיים בסוף שורת ה-if.

Forgetting the colon at the end of the if line.

if_demo.py
pages = 640
if pages > 500
    print("Thick")
מה Python עונהWhat Python says
  File "/Users/you/python-course/if_demo.py", line 2
    if pages > 500
                  ^
SyntaxError: expected ':'
בעברית פשוטה: In plain words: 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.

עוד דוגמה: מה ללבושOne more: what to wear
example.py
temp = 14
if temp > 25:
    print("T-shirt")
elif temp > 15:
    print("Sweater")
else:
    print("Coat")
פלטOutput
Coat
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

grade.py
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")
פלטOutput
ציון: 84
B
Score: 84
B
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

סימולציהSimulationאחרי שנמצא מסלול, שאר הבדיקות מדולגותOnce a path matches, the rest are skipped

מה קורה עכשיוWhat happens now

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

elif הוא כמו מכונת מיון מטבעות: המטבע נופל דרך חורים מהגדול לקטן, ונעצר בחור הראשון שהוא נכנס אליו.

elif is like a coin sorter: the coin drops past holes from largest to smallest and stops at the first one it fits.

טעות נפוצהCommon mistake

כותבים else עם תנאי.

Writing a condition after else.

grade.py
x = 5
if x > 10:
    print("big")
else x > 3:
    print("medium")
מה Python עונהWhat Python says
  File "/Users/you/python-course/grade.py", line 4
    else x > 3:
         ^
SyntaxError: expected ':'
בעברית פשוטה: In plain words: 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.

compare.py
age = 16
print(age == 16, age != 16)
print(13 <= age < 18)
print("apple" < "banana")
print("Zebra" < "apple")
פלטOutput
True False
True
True
True
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

= הוא "שים את זה בקופסה". == הוא "האם מה שבקופסה זהה לזה?". פעולה מול שאלה.

= is "put this in the box". == is "is what's in the box the same as this?". An action versus a question.

טיפTip

אותיות גדולות באות לפני קטנות בהשוואת מחרוזות. להשוואה בלי רגישות: a.lower() == b.lower().

Uppercase letters sort before lowercase. For a case-insensitive comparison: a.lower() == b.lower().

טעות נפוצהCommon mistake

משתמשים ב-= בתוך תנאי.

Using = inside a condition.

compare.py
age = 16
if age = 16:
    print("16!")
מה Python עונהWhat Python says
  File "/Users/you/python-course/compare.py", line 2
    if age = 16:
       ^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
בעברית פשוטה: In plain words: 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.

logic.py
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)
פלטOutput
מצטערים
False
Sorry
False
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

ABA and BA or B
TrueTrueTrueTrue
TrueFalseFalseTrue
FalseTrueFalseTrue
FalseFalseFalseFalse
אנלוגיה מהחייםReal-life analogy

and הוא כמו כספת עם שני מפתחות: צריך את שניהם. or הוא כמו בית עם שתי דלתות: מספיקה אחת.

and is like a safe with two keys: you need both. or is like a house with two doors: one is enough.

טעות נפוצהCommon mistake

כותבים x == 1 or 2 במקום שני תנאים מלאים. זה לא נופל, אבל תמיד True!

Writing x == 1 or 2 instead of two full conditions. It doesn't crash, but it's always True!

logic.py
x = 5
if x == 1 or x = 2:
    print("one or two")
מה Python עונהWhat Python says
  File "/Users/you/python-course/logic.py", line 2
    if x == 1 or x = 2:
                   ^
SyntaxError: invalid syntax
בעברית פשוטה: In plain words: SyntaxError: כל צד צריך תנאי שלם עם ==: 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.

עוד דוגמה: מותר לשחק?One more: can I play?
example.py
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")
פלטOutput
Play time!
Up early
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

truthy.py
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")
פלטOutput
שם (אפשר ריק): 
שלום, אורח/ת
Name (can be empty): 
Hi, guest
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

זה כמו לבדוק אם יש משהו בארנק: לא צריך לספור כמה, רק אם הוא ריק או לא.

It's like checking whether there's anything in your wallet: you don't count, you just check if it's empty.

טעות נפוצהCommon mistake

משווים מחרוזת מהקלט למספר.

Comparing a string from input with a number.

truthy.py
age = input("Age? ")
if age >= 18:
    print("adult")
מה Python עונהWhat Python says
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'
בעברית פשוטה: In plain words: 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
איפה זה נשברWhere it breaksשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיו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.

nested.py
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")
פלטOutput
אפשר לשאול עוד ספר
You can borrow another
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Python קוראתLine by line, the way Python reads it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

אנלוגיה מהחייםReal-life analogy

הזחה היא כמו תיקיות בתוך תיקיות: מה שבפנים שייך לתיקייה שעוטפת אותו.

Indentation is like folders inside folders: whatever is inside belongs to the folder around it.

טעות נפוצהCommon mistake

שוכחים להזיח את הבלוק.

Forgetting to indent the block.

nested.py
pages = 600
if pages > 500:
print("thick")
מה Python עונהWhat Python says
  File "/Users/you/python-course/nested.py", line 3
    print("thick")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2
בעברית פשוטה: In plain words: IndentationError: 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.

נבנה על ידיBuilt by Ariel Yohimovich