חלקPart 1: יסודותFoundations
כ-3 שעות (כולל הפסקה)About 3 hours (with a break)
לולאותLoops
while, for, range, break ו-continue, ולולאת תפריט.
while, for, range, break and continue, and a menu loop.
הנקודות החשובותKey points
- חוזר כל עוד התנאי TrueRepeats while the condition is True
- משהו בתוך הלולאה חייב לשנות את התנאיSomething inside must change the condition
for x in רצף:for x in sequence:- עובד על מחרוזות, רשימות ו-rangeWorks on strings, lists and range
range(5)→ 0..4range(5)→ 0..4range(1, 6)→ 1..5range(1, 6)→ 1..5- מתחילים ב-0 לפני הלולאהStart at 0 before the loop
- מוסיפים בכל סיבובAdd on every pass
breakיוצא מהלולאה מידbreakleaves the loop at once
מונחיםTerms
- לולאהloop: קוד שחוזר שוב ושוב:
whileכל עוד תנאי נכון,forעל כל פריט ברצף.Code that repeats:whileas long as a condition holds,forover each item of a sequence. - איטרציהiteration: סיבוב אחד של לולאה.One pass through a loop.
- צוברaccumulator: משתנה שמתחיל ב-0 (או ריק) ומצטבר בכל סיבוב, למשל סכום.A variable that starts at 0 (or empty) and grows each pass, like a total.
- לולאה אינסופיתinfinite loop: לולאה שהתנאי שלה אף פעם לא נהיה False. עוצרים עם Ctrl+C.A loop whose condition never becomes False. Stop it with Ctrl+C.
- rangerange: רצף מספרים:
range(5)הוא 0 עד 4,range(1, 6)הוא 1 עד 5.A sequence of numbers:range(5)is 0 to 4,range(1, 6)is 1 to 5.
Cheatsheet
whilewhile
pages_left = 50
day = 0
while pages_left > 0:
day += 1
pages_left -= 20
print(f"יום {day}: נשארו {max(pages_left, 0)}")
print("סיימתי!")pages_left = 50
day = 0
while pages_left > 0:
day += 1
pages_left -= 20
print(f"Day {day}: left {max(pages_left, 0)}")
print("Finished!")forfor
for letter in "Dune":
print(letter)
for book in ["Dune", "Emma", "Ulysses"]:
print(f"📚 {book}")rangerange
for i in range(3):
print(i, end=" ")
print()
for day in range(1, 6):
print(day, end=" ")
print()
for n in range(10, 0, -3):צובריםAccumulators
pages = [412, 96, 1036, 280]
total = 0
long_books = 0
biggest = pages[0]
for p in pages:
total += p
if p > 500:break/continuebreak/continue
for p in [96, 0, 412, -5, 280]:
if p < 0:
print("נתון שגוי, עוצרים")
break
if p == 0:
continue
print(p)for p in [96, 0, 412, -5, 280]:
if p < 0:
print("bad data, stopping")
break
if p == 0:
continue
print(p)תפריטMenu loop
count = 0
while True:
choice = input("1) הוספת ספר 2) כמה ספרים q) יציאה: ")
if choice == "1":
count += 1
print("נוסף")
elif choice == "2":count = 0
while True:
choice = input("1) add a book 2) how many q) quit: ")
if choice == "1":
count += 1
print("added")
elif choice == "2":שגיאות שפגשנוErrors we met
| שגיאהError | מה זה אומרWhat it means | מה עושיםWhat to do |
|---|---|---|
RuntimeError | לולאה אינסופית: שוכחים לעדכן את המשתנה. כאן הדפדפן עוצר אחרי כמה שניות, ובטרמינל עוצרים עם Ctrl+C. הדוגמה עוצרת בכוונה עם שגיאה כדי להראות את הרעיון.An infinite loop: forgetting to update the variable. The browser stops it after a few seconds; in a terminal press Ctrl+C. This example deliberately stops with an error to show the idea. | n אף פעם לא קטן, אז התנאי תמיד True. בתוך הלולאה חייב להיות n -= 1 או משהו דומה.n never shrinks, so the condition is always True. The loop needs n -= 1 or similar. |
SyntaxError | שוכחים את in.Forgetting in. | SyntaxError: התבנית היא for <משתנה> in <רצף>:.SyntaxError: the pattern is for <variable> in <sequence>:. |
TypeError | מעבירים ל-range מספר עשרוני.Passing a decimal to range. | TypeError: 'float' object cannot be interpreted as an integer: range עובד רק עם int.TypeError: 'float' object cannot be interpreted as an integer: range takes int only. |
AssertionError | מאפסים את הצובר בתוך הלולאה, ולכן הוא אף פעם לא מצטבר. כאן הקוד מוסיף בדיקה שמגלה את זה.Resetting the accumulator inside the loop, so it never accumulates. Here the code adds a check that catches it. | AssertionError: total = 0 צריך להיות לפני הלולאה, פעם אחת.AssertionError: total = 0 belongs before the loop, once. |
SyntaxError | משתמשים ב-break מחוץ ללולאה.Using break outside a loop. | SyntaxError: 'break' outside loop: break שייך רק לתוך for או while.SyntaxError: 'break' outside loop: break only belongs inside a for or while. |
EOFError | קוראים לתפריט בלי קלט נוסף כשהמשתמש לא בחר יציאה, והקלט נגמר.The menu keeps asking but the input ran out before the user chose to quit. | EOFError: אין יותר קלט. בטרמינל אמיתי זה קורה ב-Ctrl+D. כדאי תמיד לאפשר יציאה ברורה.EOFError: no more input. In a real terminal Ctrl+D does this. Always offer a clear way out. |