דפי עזרCheatsheets
כל דוגמת Python כאן רצה בזמן בניית האתר, והפלט שלה אמיתי. לכל דף יש עוגן לקישור ישיר.
Every Python example here ran while the site was built, and its output is real. Each sheet has an anchor for a direct link.
יסודות PythonPython basics
מפגשSession 1משתנים וטיפוסיםVariables and types
name = "Noa" # str
age = 15 # int
height = 1.62 # float
is_student = True # bool
print(type(age).__name__)פלטOutput
int
קלט והמרהInput and conversion
text = "42" # input() always returns a string
n = int(text)
price = float("9.90")
print(n + 1, price * 2)פלטOutput
43 19.8
f-stringf-strings
name, score = "Dan", 92.456
print(f"{name} scored {score:.1f}")
print(f"{7:03d}", f"{0.25:.0%}")פלטOutput
Dan scored 92.5 007 25%
תנאיםConditions
x = 7
if x > 10:
print("big")
elif x > 5:
print("medium")
else:
print("small")פלטOutput
medium
לולאותLoops
for i in range(1, 4):
print(i, end=" ")
print()
n = 3
while n > 0:
n -= 1פלטOutput
1 2 3
פונקציותFunctions
def greet(name, greeting="Hi"):
return f"{greeting}, {name}!"
print(greet("Lia"), greet("Ari", greeting="Hey"))פלטOutput
Hi, Lia! Hey, Ari!
חריגותExceptions
try:
n = int("abc")
except ValueError as e:
print("not a number:", e)
finally:
print("done")פלטOutput
not a number: invalid literal for int() with base 10: 'abc' done
מחרוזות ורשימותStrings and lists
מפגשSession 9חיתוךSlicing
s = "python"
print(s[0], s[-1], s[1:4], s[::-1])פלטOutput
p n yth nohtyp
מתודות מחרוזתString methods
t = " Hello World "
print(t.strip().lower(), t.split(), "-".join(["a", "b"]))
print("World" in t, t.count("o"), t.replace("World", "Python").strip())פלטOutput
hello world ['Hello', 'World'] a-b True 2 Hello Python
רשימותLists
nums = [3, 1, 2]
nums.append(5)
nums.insert(0, 9)
nums.remove(1)
print(nums, len(nums), sorted(nums), nums.pop())פלטOutput
[9, 3, 2] 4 [2, 3, 5, 9] 5
comprehensionComprehensions
squares = [n * n for n in range(6) if n % 2 == 0]
print(squares)פלטOutput
[0, 4, 16]
enumerate ו-zipenumerate and zip
names, ages = ["Noa", "Dan"], [15, 16]
for i, (n, a) in enumerate(zip(names, ages), start=1):
print(i, n, a)פלטOutput
1 Noa 15 2 Dan 16
מיון עם keySorting with key
words = ["kiwi", "fig", "banana"]
print(sorted(words, key=len), max(words, key=len))פלטOutput
['fig', 'kiwi', 'banana'] banana
מילונים וקבוצותDicts and sets
מפגשSession 11יצירה וגישהCreate and access
ages = {"noa": 15, "dan": 16}
ages["lia"] = 14
print(ages["noa"], ages.get("zoe", 0), "dan" in ages)פלטOutput
15 0 True
מעבר על מילוןLooping a dict
ages = {"noa": 15, "dan": 16}
for name, age in ages.items():
print(name, age)פלטOutput
noa 15 dan 16
ספירהCounting
counts = {}
for w in "a b a c a".split():
counts[w] = counts.get(w, 0) + 1
print(counts)פלטOutput
{'a': 3, 'b': 1, 'c': 1}Counter ו-defaultdictCounter and defaultdict
from collections import Counter, defaultdict
print(Counter("banana").most_common(2))
groups = defaultdict(list)
groups["red"].append("apple")
print(dict(groups))פלטOutput
[('a', 3), ('n', 2)]
{'red': ['apple']}קבוצותSets
a, b = {1, 2, 3}, {3, 4}
print(a | b, a & b, a - b, 2 in a)פלטOutput
{1, 2, 3, 4} {3} {1, 2} Truedict comprehensionDict comprehension
prices = {"pen": 4, "ink": 12}
print({k: v * 2 for k, v in prices.items() if v < 10})פלטOutput
{'pen': 8}קבצים, JSON ו-CSVFiles, JSON and CSV
מפגשSession 21כתיבה וקריאהWrite and read
from pathlib import Path
p = Path("notes.txt")
p.write_text("first\nsecond\n", encoding="utf-8")
for line in p.read_text(encoding="utf-8").splitlines():
print(line)פלטOutput
first second
with openwith open
with open("log.txt", "a", encoding="utf-8") as f:
f.write("one more line\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read().strip())פלטOutput
one more line
JSONJSON
import json
data = {"name": "Noa", "tags": ["a", "b"]}
text = json.dumps(data, ensure_ascii=False, indent=2)
print(json.loads(text)["tags"])פלטOutput
['a', 'b']
CSVCSV
import csv
with open("people.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["name", "age"])
w.writeheader()
w.writerow({"name": "Dan", "age": 16})
with open("people.csv", encoding="utf-8") as f:
print(list(csv.DictReader(f)))פלטOutput
[{'name': 'Dan', 'age': '16'}]נתיביםPaths
from pathlib import Path
here = Path(__file__).parent
print((here / "data" / "file.json").name, Path("a/b.txt").suffix)פלטOutput
file.json .txt
Git ו-GitHubGit and GitHub
מפגשSession 20התחלהGetting started
git init
git status
git add main.py
git commit -m "First version"היסטוריה והבדליםHistory and differences
git log --oneline
git diff
git diff --stagedענפיםBranches
git switch -c feature
git switch main
git merge featureGitHubGitHub
git remote add origin https://github.com/USER/REPO.git
git push -u origin main
git pullביטולUndo
git restore main.py # discard unsaved changes
git restore --staged main.py # unstage
git commit --amend # fix the last messageקובץ .gitignoreA .gitignore file
__pycache__/
.venv/
*.pyc
.envpytestpytest
מפגשSession 19בדיקה ראשונהA first test
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
test_add()
print("ok")פלטOutput
ok
בדיקת חריגהTesting an exception
import pytest
def test_bad_int():
with pytest.raises(ValueError):
int("x")
test_bad_int()
print("ok")פלטOutput
ok
פרמטריםParametrize
import pytest
@pytest.mark.parametrize("n, expected", [(1, 1), (4, 16)])
def test_square(n, expected):
assert n * n == expected
print("collected by pytest")פלטOutput
collected by pytest
fixtureFixtures
import pytest
@pytest.fixture
def shelf():
return ["Dune", "Emma"]
def test_len(shelf):
assert len(shelf) == 2
print("pytest passes the fixture in")פלטOutput
pytest passes the fixture in
הרצהRunning
python3 -m pytest
python3 -m pytest -q test_shelf.py
python3 -m pytest -k add -xpandaspandas
מפגשSession 24DataFrameA DataFrame
import pandas as pd
df = pd.DataFrame({"name": ["Noa", "Dan", "Lia"], "km": [5.0, 12.5, 3.2], "team": ["red", "blue", "red"]})
print(df.head(2))פלטOutput
name km team 0 Noa 5.0 red 1 Dan 12.5 blue
סינון ומיוןFilter and sort
import pandas as pd
df = pd.DataFrame({"name": ["Noa", "Dan", "Lia"], "km": [5.0, 12.5, 3.2]})
print(df[df["km"] > 4].sort_values("km", ascending=False))פלטOutput
name km 1 Dan 12.5 0 Noa 5.0
עמודה חדשהA new column
import pandas as pd
df = pd.DataFrame({"km": [5.0, 12.5]})
df["miles"] = (df["km"] * 0.621).round(1)
print(df)פלטOutput
km miles 0 5.0 3.1 1 12.5 7.8
קיבוץGroup by
import pandas as pd
df = pd.DataFrame({"team": ["red", "blue", "red"], "km": [5.0, 12.5, 3.2]})
print(df.groupby("team")["km"].agg(["sum", "mean"]).round(1))פלטOutput
sum mean team blue 12.5 12.5 red 8.2 4.1
קריאה ושמירהRead and save
import pandas as pd
pd.DataFrame({"a": [1, 2]}).to_csv("out.csv", index=False)
print(pd.read_csv("out.csv").shape)פלטOutput
(2, 1)
ערכים חסריםMissing values
import pandas as pd
df = pd.DataFrame({"x": [1, None, 3]})
print(df["x"].isna().sum(), df["x"].fillna(0).tolist())פלטOutput
1 [1.0, 0.0, 3.0]
pygamepygame
מפגשSession 37שלד משחקA game skeleton
import pygame
pygame.init()
screen = pygame.display.set_mode((320, 200))
clock = pygame.time.Clock()
running, frames = True, 0
while running and frames < 3:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 20, 40))
pygame.display.flip()
dt = clock.tick(60) / 1000
frames += 1
pygame.quit()
print("frames:", frames)פלטOutput
frames: 3
screen.png
Rect והתנגשותRect and collisions
import pygame
a, b = pygame.Rect(0, 0, 20, 20), pygame.Rect(15, 10, 20, 20)
print(a.colliderect(b), a.clip(b).size, b.center)פלטOutput
True (5, 10) (25, 20)
Vector2Vector2
import pygame
v = pygame.Vector2(3, 4)
print(v.length(), v.normalize(), v * 2)פלטOutput
5.0 [0.6, 0.8] [6, 8]
מקשיםKeys
import pygame
pygame.init()
keys = pygame.key.get_pressed()
dx = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
print("dx:", dx)
pygame.quit()פלטOutput
dx: 0
טקסטText
import pygame
pygame.init()
font = pygame.font.Font(None, 28)
label = font.render("Score 10", True, (255, 255, 255))
print(label.get_width() > 0)
pygame.quit()פלטOutput
True