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

PythonPython

דפי עזר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
cheat_python_basics.py
name = "Noa"          # str
age = 15               # int
height = 1.62          # float
is_student = True      # bool
print(type(age).__name__)
פלטOutput
int
קלט והמרהInput and conversion
cheat_python_basics.py
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
cheat_python_basics.py
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
cheat_python_basics.py
x = 7
if x > 10:
    print("big")
elif x > 5:
    print("medium")
else:
    print("small")
פלטOutput
medium
לולאותLoops
cheat_python_basics.py
for i in range(1, 4):
    print(i, end=" ")
print()
n = 3
while n > 0:
    n -= 1
פלטOutput
1 2 3 
פונקציותFunctions
cheat_python_basics.py
def greet(name, greeting="Hi"):
    return f"{greeting}, {name}!"

print(greet("Lia"), greet("Ari", greeting="Hey"))
פלטOutput
Hi, Lia! Hey, Ari!
חריגותExceptions
cheat_python_basics.py
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
cheat_strings_lists.py
s = "python"
print(s[0], s[-1], s[1:4], s[::-1])
פלטOutput
p n yth nohtyp
מתודות מחרוזתString methods
cheat_strings_lists.py
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
cheat_strings_lists.py
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
cheat_strings_lists.py
squares = [n * n for n in range(6) if n % 2 == 0]
print(squares)
פלטOutput
[0, 4, 16]
enumerate ו-zipenumerate and zip
cheat_strings_lists.py
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
cheat_strings_lists.py
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
cheat_dicts.py
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
cheat_dicts.py
ages = {"noa": 15, "dan": 16}
for name, age in ages.items():
    print(name, age)
פלטOutput
noa 15
dan 16
ספירהCounting
cheat_dicts.py
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
cheat_dicts.py
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
cheat_dicts.py
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} True
dict comprehensionDict comprehension
cheat_dicts.py
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
cheat_files.py
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
cheat_files.py
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
cheat_files.py
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
cheat_files.py
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
cheat_files.py
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
Terminal
git init
git status
git add main.py
git commit -m "First version"
היסטוריה והבדליםHistory and differences
Terminal
git log --oneline
git diff
git diff --staged
ענפיםBranches
Terminal
git switch -c feature
git switch main
git merge feature
GitHubGitHub
Terminal
git remote add origin https://github.com/USER/REPO.git
git push -u origin main
git pull
ביטולUndo
Terminal
git restore main.py          # discard unsaved changes
git restore --staged main.py # unstage
git commit --amend           # fix the last message
קובץ .gitignoreA .gitignore file
Terminal
__pycache__/
.venv/
*.pyc
.env

pytestpytest

מפגשSession 19
בדיקה ראשונהA first test
cheat_pytest.py
def add(a, b):
    return a + b

def test_add():
    assert add(2, 3) == 5

test_add()
print("ok")
פלטOutput
ok
בדיקת חריגהTesting an exception
cheat_pytest.py
import pytest

def test_bad_int():
    with pytest.raises(ValueError):
        int("x")

test_bad_int()
print("ok")
פלטOutput
ok
פרמטריםParametrize
cheat_pytest.py
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
cheat_pytest.py
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
Terminal
python3 -m pytest
python3 -m pytest -q test_shelf.py
python3 -m pytest -k add -x

pandaspandas

מפגשSession 24
DataFrameA DataFrame
cheat_pandas.py
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
cheat_pandas.py
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
cheat_pandas.py
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
cheat_pandas.py
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
cheat_pandas.py
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
cheat_pandas.py
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
cheat_pygame.py
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
screen.png
Rect והתנגשותRect and collisions
cheat_pygame.py
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
cheat_pygame.py
import pygame
v = pygame.Vector2(3, 4)
print(v.length(), v.normalize(), v * 2)
פלטOutput
5.0 [0.6, 0.8] [6, 8]
מקשיםKeys
cheat_pygame.py
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
cheat_pygame.py
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

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