טיפוסים ומספריםTypes & numbers
int, float, bool, המרות בין טיפוסים, עיגול, ומה קורה כשמערבבים.
int, float, bool, converting between types, rounding, and what happens when you mix them.
01כל ערך שייך לטיפוסEvery value has a type
לכל ערך ב-Python יש טיפוס. הטיפוס קובע מה מותר לעשות איתו: מספרים אפשר לחלק, טקסט אפשר להפוך לאותיות גדולות. הפונקציה type מראה את הטיפוס.
Every value in Python has a type. The type decides what you can do with it: numbers can be divided, text can be uppercased. The type function shows the type.
print(type(42))
print(type(3.5))
print(type("42"))
print(type(True))
print(7 / 2, type(7 / 2))<class 'int'> <class 'float'> <class 'str'> <class 'bool'> 3.5 <class 'float'>
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
טיפוס הוא כמו סוג הכלי במטבח: בכוס מוזגים, בסכין חותכים. אותו דבר (42) בכוס ובצלחת מתנהג אחרת.
A type is like the kind of kitchenware: you pour into a cup, you cut with a knife. The same thing (42) behaves differently in a cup and on a plate.
מחברים מספר לטקסט. ל-Python אין דרך לנחש אם התכוונתם ל-"55" או ל-10.
Adding a number to text. Python can't guess whether you meant "55" or 10.
print("5" + 5)Traceback (most recent call last):
File "/Users/you/python-course/type_demo.py", line 1, in <module>
print("5" + 5)
~~~~^~~
TypeError: can only concatenate str (not "int") to strTypeError: ממירים קודם: int("5") + 5 נותן 10, "5" + str(5) נותן "55".TypeError: convert first: int("5") + 5 gives 10, "5" + str(5) gives "55".צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
02המרות: int, float, strConversions: int, float, str
המרת טיפוס יוצרת ערך חדש מטיפוס אחר. הכי שימושי: להמיר את מה ש-input מחזירה למספר, כדי שאפשר יהיה לחשב איתו.
Type conversion makes a new value of a different type. Most useful: turning what input returns into a number so you can calculate with it.
age = int(input("גיל: "))
print(f"בשנה הבאה תהיו בני {age + 1}")
price = float("19.90")
print(price * 2)
print(str(2026) + "!")age = int(input("Age: "))
print(f"Next year you will be {age + 1}")
price = float("19.90")
print(price * 2)
print(str(2026) + "!")גיל: 30 בשנה הבאה תהיו בני 31 39.8 2026!
Age: 30 Next year you will be 31 39.8 2026!
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
המרה היא כמו להחליף כסף בדלפק: נותנים שקלים ומקבלים דולרים. הערך המקורי לא משתנה, מקבלים ערך חדש.
Conversion is like a currency exchange counter: you hand over shekels and get dollars. The original stays the same; you get a new value.
ממירים למספר טקסט שאינו מספר.
Converting text that isn't a number.
pages = int("96 pages")Traceback (most recent call last):
File "/Users/you/python-course/convert.py", line 1, in <module>
pages = int("96 pages")
ValueError: invalid literal for int() with base 10: '96 pages'ValueError: int מקבלת רק ספרות. בהמשך (מפגש 11) נתפוס שגיאה כזו בלי שהתוכנית תיפול.ValueError: int accepts digits only. Later (session 11) we catch this without crashing.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
"7" הוא טקסט ו-7 הוא מספר. רואים מה קורה כשמחברים כל אחד מהם.
"7" is text and 7 is a number. See what happens when we add each.
a = "7"
b = "3"
print(a + b)
print(int(a) + int(b))
print(float("2.5") * 2)73 10 5.0
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
03אמת ושקר: boolTrue and False: bool
טיפוס בוליאני יש לו שני ערכים בלבד: True ו-False. השוואות כמו > או == מחזירות ערך כזה. במפגש 5 נשתמש בהם כדי לקבל החלטות.
A boolean (bool) type has just two values: True and False. Comparisons like > or == return one. In session 5 we use them to make decisions.
pages = 412
print(pages > 300)
print(pages == 400)
print(pages != 400)
print(bool(0), bool(7), bool(""), bool("hi"))True False True False True False True
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
bool הוא מתג אור: דלוק או כבוי, אין מצב שלישי.
A bool is a light switch: on or off, no third option.
כותבים true באות קטנה. ב-Python זה True עם T גדולה.
Writing true in lowercase. In Python it's True with a capital T.
done = trueTraceback (most recent call last):
File "/Users/you/python-course/bools.py", line 1, in <module>
done = true
^^^^
NameError: name 'true' is not defined. Did you mean: 'True'?NameError: true הוא סתם שם לא מוכר. כותבים True.NameError: true is just an unknown name. Write True.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
השוואה תמיד נותנת True או False.
A comparison always gives True or False.
age = 12
print(age > 10)
print(age == 12)
print(age < 5)
is_teen = age >= 13
print(is_teen)True True False False
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
04עיגול ועשרונייםRounding and decimals
מחשבים שומרים מספרים עשרוניים בבסיס 2, ולכן חלק מהם לא מדויקים לגמרי. זה לא באג של Python, ככה עובדים כל המחשבים. לתצוגה מעגלים עם round או עם עיצוב ב-f-string.
Computers store decimals in base 2, so some aren't perfectly exact. It's not a Python bug; every computer works this way. For display, round with round or format in an f-string.
print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(round(2.675, 2))
price = 19.9
print(f"{price:.2f} ₪")
print(round(7.5), round(8.5))0.30000000000000004 0.3 2.67 19.90 ₪ 8 8
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
זה כמו לכתוב שליש כמספר עשרוני: 0.3333... תמיד חסר קצת. מחשב בבסיס 2 נתקל באותה בעיה עם 0.1.
It's like writing a third as a decimal: 0.3333... is always a bit short. A base-2 computer hits the same problem with 0.1.
round(7.5) ו-round(8.5) נותנים 8 ו-8: Python מעגלת חצאים למספר הזוגי הקרוב. לכסף אמיתי משתמשים במודול decimal.
round(7.5) and round(8.5) both give 8: Python rounds halves to the nearest even number. For real money use the decimal module.
ממירים מספר עם פסיק עשרוני. Python מבינה רק נקודה.
Converting a number with a decimal comma. Python only understands a dot.
price = float("19,90")Traceback (most recent call last):
File "/Users/you/python-course/round.py", line 1, in <module>
price = float("19,90")
ValueError: could not convert string to float: '19,90'ValueError: משתמשים בנקודה: "19.90". אם הקלט מגיע עם פסיק: text.replace(",", ".").ValueError: use a dot: "19.90". If input comes with a comma: text.replace(",", ".").צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05המודול mathThe math module
מודול הוא ארגז כלים מוכן. import math נותן שורשים, פאי, עיגול למעלה ולמטה ועוד. פונקציות כמו abs, min ו-max מובנות ולא צריך לייבא אותן.
A module is a ready toolbox. import math gives square roots, pi, rounding up and down, and more. Functions like abs, min and max are built in and need no import.
import math
print(math.sqrt(81))
print(round(math.pi, 3))
print(math.ceil(412 / 30), "ימים לסיים ספר")
print(math.floor(9.99))
print(abs(-5), min(3, 9, 1), max(3, 9, 1))import math
print(math.sqrt(81))
print(round(math.pi, 3))
print(math.ceil(412 / 30), "days to finish a book")
print(math.floor(9.99))
print(abs(-5), min(3, 9, 1), max(3, 9, 1))9.0 3.142 14 ימים לסיים ספר 9 5 1 9
9.0 3.142 14 days to finish a book 9 5 1 9
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
import הוא כמו להוציא ארגז כלים מהמחסן. הכלים היו שם תמיד, רק צריך להביא אותם לשולחן.
import is like fetching a toolbox from the shed. The tools were always there; you just bring them to the table.
משתמשים ב-math בלי import.
Using math without import.
print(math.sqrt(16))Traceback (most recent call last):
File "/Users/you/python-course/mathdemo.py", line 1, in <module>
print(math.sqrt(16))
^^^^
NameError: name 'math' is not defined. Did you forget to import 'math'?NameError: name 'math' is not defined: מוסיפים import math בראש הקובץ.NameError: name 'math' is not defined: add import math at the top of the file.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
06ביטויים וסדר פעולותExpressions and precedence
ביטוי הוא כל צירוף שמחושב לערך אחד. Python מחשבת לפי סדר קבוע: חזקה, אחר כך כפל וחילוק, ובסוף חיבור וחיסור. כשיש ספק, סוגריים הופכים את הכוונה לברורה.
An expression is any combination that evaluates to one value. Python follows a fixed order: power, then multiply and divide, then add and subtract. When in doubt, parentheses make the intent clear.
minutes = 135
hours = minutes // 60
rest = minutes % 60
print(f"{hours}:{rest:02d}")
print(2 + 3 * 2 ** 2)
print((2 + 3) * 2 ** 2)2:15 14 20
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
סדר פעולות הוא כמו סדר לבישה: גרביים לפני נעליים. אם רוצים סדר אחר, אומרים במפורש (סוגריים).
Precedence is like the order of getting dressed: socks before shoes. For a different order, say so explicitly (parentheses).
שוכחים לסגור סוגריים בביטוי ארוך.
Forgetting to close a parenthesis in a long expression.
total = (2 + 3 * (4 - 1)
print(total) File "/Users/you/python-course/expr.py", line 1
total = (2 + 3 * (4 - 1)
^
SyntaxError: '(' was never closedSyntaxError: '(' was never closed: סופרים סוגריים פותחים וסוגרים.SyntaxError: '(' was never closed: count opening and closing brackets.סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.