This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · Halaman ini memerlukan browser terbaru (dengan dukungan SharedArrayBuffer). Silakan perbarui Chrome, Edge, Firefox, atau Safari ke versi terbaru.
Python runs your code one line at a time. Each line is a statement 语句. A program 程序 is just a list of statements that run from top to bottom.
The print() function shows text on the screen. This is called output 输出. Text inside quotes is a string 字符串.
Each print() starts a new line.
Quotes can be "double" or 'single' — both make a string.
A program does nothing until you run it.
Bahasa Indonesia
Python menjalankan kode Anda satu baris sekaligus. Setiap baris adalah pernyataan. Program hanyalah daftar pernyataan yang berjalan dari atas ke bawah.
Fungsi print() menampilkan teks di layar. Ini disebut output. Teks di dalam tanda kutip adalah string.
print("Hello, world!")
print("I am learning Python")
Setiap print() memulai baris baru.
Tanda kutip bisa "double" atau 'single' — keduanya menghasilkan string.
Program tidak melakukan apa pun sampai Anda menjalankannya.
Source code runs through the interpreter to produce output
1.2
Komentar & gaya kode
English
A comment 注释 starts with #. Python ignores everything after the # on that line. Comments explain your code to people; they do not change what the code does.
Good style makes code easy to read:
Use clear names that say what a value means.
Put one statement on each line.
Do not add spaces at the start of a normal line. In Python, spacing at the start (indentation 缩进) has a special meaning, so a wrong space gives an error 错误.
Bahasa Indonesia
Komentar dimulai dengan #. Python mengabaikan segalanya setelah # pada baris itu. Komentar menjelaskan kode Anda kepada orang lain; mereka tidak mengubah apa yang dilakukan kode.
# This line is a note for humans
print("Hi") # you can also comment at the end of a line
Gaya yang baik membuat kode mudah dibaca:
Gunakan nama yang jelas untuk menunjukkan arti suatu nilai.
Letakkan satu pernyataan dalam setiap baris.
Jangan tambahkan spasi di awal baris biasa. Di Python, spasi di awal (indentasi) memiliki makna khusus, sehingga spasi yang salah akan menyebabkan error.
1.3
Input, proses, output
English
Many programs follow a simple plan: input 输入 → process → output. You get some data, do something with it, then show a result.
The input() function reads text that the user types. It always gives back a string.
input() waits for the user to type and press Enter.
Store the typed text in a variable 变量 so you can use it later.
Because input() returns a string, change it with int(...) first if you need a number.
Common mistakes
Forgetting the quotes: print(Hello) looks for a variable named Hello and raises a NameError. Text needs quotes: print("Hello").
A stray space at the start of a line: Python reads indentation as structure, so it raises an IndentationError.
Assuming input() returns a number. It always returns a string, so wrap it in int(...) before doing any maths.
Bahasa Indonesia
Banyak program mengikuti rencana sederhana: input → proses → output. Anda mendapatkan data, memprosesnya, lalu menampilkan hasilnya.
Fungsi input() membaca teks yang diketik pengguna. Fungsi ini selalu mengembalikan string.
name = input("What is your name? ")
print("Hello, " + name)
input() menunggu pengguna mengetik dan menekan Enter.
Simpan teks yang diketik ke dalam variabel agar dapat digunakan nanti.
Karena input() mengembalikan string, ubah terlebih dahulu dengan int(...) jika Anda memerlukan angka.
Kesalahan umum
Lupa tanda kutip: print(Hello) mencari variabel bernama Hello dan memicu NameError. Teks perlu tanda kutip: print("Hello").
Spasi tak terduga di awal baris: Python membaca indentasi sebagai struktur, sehingga memicu IndentationError.
Menganggap input() mengembalikan angka. Fungsi ini selalu mengembalikan string, jadi bungkus dengan int(...) sebelum melakukan matematika.
2Variables, types & operators · Variabel, tipe & operator
A variable 变量 is a name for a value 值. You make one with =, which is called assignment 赋值. The name goes on the left; the value goes on the right.
Now age holds 17. Use the name anywhere you need the value, and change it later:
The = sign does not mean "equal". It means "store the right side under the left name".
To test if two values are equal, use == (see below).
Bahasa Indonesia
Variabel adalah nama untuk sebuah nilai. Anda membuatnya dengan =, yang disebut penugasan. Nama diletakkan di kiri; nilai diletakkan di kanan.
age = 17
name = "Mei"
price = 9.99
print(age, name, price)
Sekarang age menyimpan 17. Gunakan nama tersebut di mana saja Anda membutuhkan nilai, dan ubah kemudian:
age = 17
age = age + 1 # age is now 18
print(age)
Setiap nama variabel menunjuk ke nilai dalam memori
Tanda = tidak berarti "sama dengan". Artinya "simpan sisi kanan di bawah nama sisi kiri".
Untuk menguji apakah dua nilai sama, gunakan == (lihat di bawah).
2.2
Angka: int & float
English
Python has two main number types. An integer 整数 (int) is a whole number like 17. A float 浮点数 (float) has a decimal point like 9.99.
These operators 运算符 work on numbers:
Operator
Meaning
Example
Result
+
add
3 + 2
5
-
subtract
3 - 2
1
*
multiply
3 * 2
6
/
divide (always float)
7 / 2
3.5
//
integer divide
7 // 2
3
%
remainder (modulo)
7 % 2
1
**
power
2 ** 3
8
/ always gives a float, so 4 / 2 is 2.0.
// and % go together: 17 // 5 is 3, and 17 % 5 is 2.
Bahasa Indonesia
Python memiliki dua jenis angka utama. Integer (int) adalah bilangan bulat seperti 17. Float (float) memiliki titik desimal seperti 9.99.
Operator-operator ini bekerja pada angka:
Operator
Makna
Contoh
Hasil
+
tambah
3 + 2
5
-
kurang
3 - 2
1
*
kali
3 * 2
6
/
bagi (selalu float)
7 / 2
3.5
//
bagi bulat
7 // 2
3
%
sisa (modulo)
7 % 2
1
**
pangkat
2 ** 3
8
/ selalu menghasilkan float, sehingga 4 / 2 adalah 2.0.
// dan % berjalan beriringan: 17 // 5 adalah 3, dan 17 % 5 adalah 2.
2.3
Ekspresi & konversi tipe
English
An expression 表达式 is anything that has a value, like 3 + 4 * 2. Python uses normal maths order (* and / before + and -); add brackets to make the order clear.
input() gives a string, so convert it before doing maths. Changing a value from one type to another is type conversion 类型转换:
int("abc") fails, so only convert text that looks like a number.
Mixing types fails too: "age: " + 17 is an error; write "age: " + str(17).
Bahasa Indonesia
Ekspresi adalah segala sesuatu yang memiliki nilai, seperti 3 + 4 * 2. Python menggunakan urutan matematika standar (* dan / sebelum + dan -); gunakan kurung untuk memperjelas urutan.
input() menghasilkan string, jadi konversikan sebelum melakukan matematika. Mengubah nilai dari satu tipe ke tipe lain disebut konversi tipe:
age = int("17") # text "17" -> number 17
price = float("9.99") # text -> 9.99
label = str(17) # number -> text "17"
print(age, price, label)
int("abc") gagal, jadi hanya konversikan teks yang terlihat seperti angka.
Mencampur tipe juga gagal: "age: " + 17 adalah error; tulis "age: " + str(17).
2.4
Boolean & perbandingan
English
A Boolean 布尔值 is one of just two values: True or False. A comparison 比较 gives back a Boolean.
Operator
Meaning
==
equal to
!=
not equal to
<>
less than / greater than
<=>=
less / greater than or equal to
Join comparisons with and, or, not:
Common mistakes
/ always gives a float, even 4 / 2 is 2.0. Use // when you want a whole number.
Using = where you mean ==: = assigns a value, == tests whether two values are equal.
Joining a string and a number: "age: " + 5 raises a TypeError. Convert first with str(5).
Floats are not exact, so 0.1 + 0.2 is not exactly 0.3 — avoid == on float results.
Bahasa Indonesia
Boolean adalah salah satu dari hanya dua nilai: True atau False. Perbandingan mengembalikan nilai Boolean.
A comparison 比较 gives a Boolean 布尔值 — either True or False.
Bahasa Indonesia
Program memilih apa yang harus dilakukan dengan if. Program menjalankan blok yang terindentasi hanya ketika kondisi bernilai benar. Baris if diakhiri dengan titik dua.
score = 72
if score >= 60:
print("pass")
# pass
Tambahkan elif (else-if) untuk lebih banyak kasus dan else untuk "segala sesuatu lainnya". Python hanya menjalankan cabang pertama yang bernilai benar, lalu melewatkan sisanya.
score = 72
if score >= 80:
print("A")
elif score >= 60:
print("B")
else:
print("fail")
# B
Bandingkan nilai dengan == (sama dengan), != (tidak sama dengan), <, >, <=, >=.
Perbandingan menghasilkan nilai Boolean — yaitu True atau False.
if / elif / else: hanya satu cabang yang berjalan
4.2
Menggabungkan kondisi
English
Join conditions with and, or, not. and needs both sides true; or needs either side true; not flips a Boolean.
Use brackets to make the order clear: (a or b) and c.
Common mistakes
Write elif, not else if.
Every if / elif / else line ends with a colon :, and its body must be indented.
if x = 5: is an error — use == to compare.
else takes no condition; only if and elif do.
Bahasa Indonesia
Gabungkan kondisi menggunakan and, or, not. and memerlukan kedua sisi bernilai benar; or memerlukan salah satu sisi bernilai benar; not membalik nilai Boolean.
age = 16
has_ticket = True
if age >= 18 and has_ticket:
print("entry allowed")
else:
print("entry refused")
# entry refused
Gunakan tanda kurung untuk memperjelas urutan: (a or b) and c.
temp = 30
if temp > 25 and not temp > 35:
print("warm but ok")
# warm but ok
Kesalahan umum
Tulis elif, bukan else if.
Setiap baris if / elif / else diakhiri dengan titik dua :, dan isinya harus diindentasi.
if x = 5: adalah kesalahan — gunakan == untuk membandingkan.
else tidak menerima kondisi; hanya if dan elif yang melakukannya.
grid = [[1, 2], [3, 4]]
for row in grid:
for value in row:
print(value, end=" ")
print() # 1 2 3 4
6.4
List comprehension
English
A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].
Add if to keep only some items.
Bahasa Indonesia
List comprehension membangun list baru dalam satu baris: [expression for item in sequence].
squares = [x * x for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
Tambahkan if untuk mempertahankan hanya beberapa item.
evens = [n for n in range(10) if n % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
6.5
Tuples & sets
English
A tuple 元组 is a fixed sequence in round brackets. It cannot be changed after it is made — use one for values that belong together, and unpack 解包 it into names.
A function that needs to hand back two results returns a tuple:
A set 集合 stores each value once, with no order. It is perfect for removing duplicates and for fast membership tests 成员测试.
Common mistakes
b = a does not copy a list: both names point to the same list, so changing one changes the other. Use a.copy() or a[:].
The last item is a[-1]; a[len(a)] is out of range.
append adds ONE item; use extend or + to join another list.
Building a grid with [[0]*3]*3 makes three copies of the same row. Build the rows in a loop instead.
A tuple with one item needs a comma: (5,), not (5).
A set has no order and no duplicates, so you cannot index it with s[0].
Bahasa Indonesia
Tuple adalah sekuens tetap dalam tanda kurung bulat. Tidak dapat diubah setelah dibuat — gunakan untuk nilai yang terkait bersama, dan buka menjadi nama-nama.
point = (3, 4)
x, y = point # unpacking
print(x, y) # 3 4
Fungsi yang perlu mengembalikan dua hasil mengembalikan tuple:
Tetapkan ke kunci untuk menambahkannya, atau mengubah yang sudah ada.
student = {"name": "Mei"}
student["score"] = 88 # add a new key
student["score"] = 90 # update the value
print(student) # {'name': 'Mei', 'score': 90}
Memeriksa dan looping
Gunakan in untuk menguji kunci. Loop atas kuncinya, atau loop atas .items() untuk mendapatkan kunci dan nilainya.
student = {"name": "Mei", "score": 90}
print("score" in student) # True
for key, value in student.items():
print(key, "=", value)
# name = Mei
# score = 90
.get(key, default) mengembalikan default ketika kunci hilang — tanpa error.
Kode di dalamnya hanya berjalan ketika Anda memanggil fungsi.
def mendefinisikan; call menjalankan; return mengirim nilai kembali
8.2
Nilai pengembalian
English
A function can return 返回 a value with return. The call then stands for that value.
return ends the function at once. A function with no return gives None.
Bahasa Indonesia
Fungsi dapat mengembalikan nilai dengan return. Pemanggilan kemudian merepresentasikan nilai tersebut.
def square(n):
return n * n
print(square(5)) # 25
print(square(3) + 1) # 10
return mengakhiri fungsi segera. Fungsi tanpa return memberikan None.
8.3
Parameter, argumen & jangkauan
English
A parameter 形参 is the name in the def. An argument 实参 is the value you pass in.
A variable made inside a function is local 局部 — it exists only there. That region is its scope 作用域.
A parameter can have a default value 默认值, used when the caller leaves it out:
Bahasa Indonesia
Parameter adalah nama dalam def. Argumen adalah nilai yang Anda masukkan.
def power(base, exp): # base, exp are parameters
return base ** exp
print(power(2, 3)) # 8 (2 and 3 are arguments)
Variabel yang dibuat di dalam fungsi bersifat lokal — ia hanya ada di sana. Wilayah itu adalah jangkauannya.
def f():
x = 10 # local to f
return x
print(f()) # 10
# print(x) here would be an error: x is not defined outside f
Parameter dapat memiliki nilai default, digunakan ketika pemanggil melewatkannya:
def greet(name, greeting="Hello"):
return greeting + ", " + name
print(greet("Mei")) # Hello, Mei
print(greet("Sam", "Welcome")) # Welcome, Sam
8.4
Abstraksi prosedural
English
Procedural abstraction 过程抽象 means hiding details behind a name. You use a function by its name and what it does, not by how it works.
A good function does one job, has a clear name, and avoids repeating code.
Bahasa Indonesia
Abstraksi prosedural berarti menyembunyikan detail di balik sebuah nama. Anda menggunakan fungsi berdasarkan namanya dan apa yang dilakukannya, bukan bagaimana cara kerjanya.
def area_of_rectangle(w, h):
return w * h
print(area_of_rectangle(4, 5)) # 20
Fungsi yang baik melakukan satu tugas, memiliki nama yang jelas, dan menghindari pengulangan kode.
8.5
Modul & impor
English
A module 模块 is a file of ready-made functions. Bring one in with import 导入.
Common mistakes
A function returns None unless you write return. Printing is not the same as returning.
Never use a mutable default like def f(x=[]) — the same list is shared between all calls.
A variable made inside a function is local and cannot be seen outside it.
Run a function with f(); writing f on its own only names it.
Bahasa Indonesia
Modul adalah file berisi fungsi siap pakai. Masukkan dengan import.
import random
random.seed(0) # makes the result repeatable
print(random.randint(1, 6)) # a dice roll
import math
print(math.sqrt(16)) # 4.0
Kesalahan umum
Fungsi mengembalikan None kecuali Anda menulis return. Mencetak (printing) tidak sama dengan mengembalikan (returning).
Jangan gunakan default yang dapat diubah seperti def f(x=[]) — daftar yang sama akan dibagi antara semua pemanggilan.
Variabel yang dibuat di dalam fungsi bersifat lokal dan tidak dapat dilihat di luarnya.
Jalankan fungsi dengan f(); menulis f sendiri hanya memberinya nama.
Code can fail in three ways. A syntax error 语法错误 breaks Python's rules, so it never runs. A runtime error 运行时错误 happens while running, like dividing by zero. A logic error 逻辑错误 runs but gives the wrong answer.
Python prints a traceback 回溯 showing where it failed. Read it from the bottom up.
Bahasa Indonesia
Kode dapat gagal dalam tiga cara. Kesalahan sintaks melanggar aturan Python, sehingga tidak pernah berjalan. Kesalahan runtime terjadi saat berjalan, seperti membagi dengan nol. Kesalahan logika berjalan tetapi memberikan jawaban yang salah.
# A runtime error, caught so this block still finishes:
try:
print(10 / 0)
except ZeroDivisionError:
print("cannot divide by zero")
# cannot divide by zero
Python mencetak traceback yang menunjukkan di mana kegagalan terjadi. Bacalah dari bawah ke atas.
Kesalahan Python umum: Syntax, Name, Type, Index
9.2
try / except / raise
English
Wrap risky code in try. If it fails, except catches the exception 异常 and handles 处理 it, instead of crashing.
Catch a specific type (ValueError, ZeroDivisionError, …).
raise makes your own error on purpose.
Bahasa Indonesia
Bungkus kode berisiko dalam try. Jika gagal, except menangkap pengecualian dan menanganinya, alih-alih membuat program crash.
Tangkap tipe spesifik (ValueError, ZeroDivisionError, …).
raise membuat kesalahan Anda sendiri dengan sengaja.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
try:
set_age(-1)
except ValueError as err:
print("error:", err)
# error: age cannot be negative
9.3
Pengujian & ketahanan
English
A test 测试 checks that code gives the right answer. Try normal cases and edge cases 边界情形 — empty input, zero, very large values.
Robust 健壮 code does not crash on strange input; it handles it gracefully.
Common mistakes
Do not use a bare except: — catch the specific error, e.g. except ValueError:.
A syntax error stops the whole program before it runs, so fix those first.
Test the edge cases (empty input, zero, the largest value), not just the easy one.
Bahasa Indonesia
Pengujian memeriksa bahwa kode memberikan jawaban yang benar. Cobalah kasus normal dan kasus batas — input kosong, nol, nilai sangat besar.
A text file 文本文件 stores text on disk. Open it with open(name, mode) where mode 模式 says read or write. Always use with, which closes the file for you.
Writing
Mode "w" writes a new file and erases any old one.
Reading
Mode "r" (the default) reads. .read() returns the whole file as one string.
Line by line
Loop over the file to get one line at a time. .strip() removes 去除 the newline 换行符 at the end.
Appending
Mode "a" appends 追加 — it adds to the end without erasing.
Mode
Meaning
"r"
read (default)
"w"
write (erases first)
"a"
append (add to the end)
Common mistakes
Always close a file, or use with open(...) as f: which closes it for you.
read() gives the whole file as one string, and each line still ends with \n.
Opening with "w" erases the file first; use "a" to add to the end.
Bahasa Indonesia
File teks menyimpan teks di disk. Buka dengan open(name, mode) di mana mode menyatakan read atau write. Selalu gunakan with, yang menutup file untuk Anda.
Menulis
Mode "w" menulis file baru dan menghapus yang lama.
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
print("saved") # saved
Membaca
Mode "r" (default) membaca. .read() mengembalikan seluruh file sebagai satu string.
with open("notes.txt", "w") as f:
f.write("hello\nworld\n")
with open("notes.txt") as f:
print(f.read().strip()) # hello / world
Baris demi baris
Loop melalui file untuk mendapatkan satu baris sekaligus. .strip() menghapus newline di akhir.
with open("data.txt", "w") as f:
f.write("Mei,88\nSam,71\n")
with open("data.txt") as f:
for line in f:
name, score = line.strip().split(",")
print(name, "scored", score)
# Mei scored 88
# Sam scored 71
Melampirkan
Mode "a" melampirkan — menambahkan ke akhir tanpa menghapus.
with open("log.txt", "w") as f:
f.write("line 1\n")
with open("log.txt", "a") as f:
f.write("line 2\n")
with open("log.txt") as f:
print(f.read().strip()) # line 1 / line 2
Mode
Makna
"r"
baca (default)
"w"
tulis (hapus dulu)
"a"
lampirkan (tambah ke akhir)
Kesalahan umum
Selalu tutup file, atau gunakan with open(...) as f: yang menutupnya untuk Anda.
read() memberikan seluruh file sebagai satu string, dan setiap baris masih berakhir dengan \n.
Membuka dengan "w" menghapus file terlebih dahulu; gunakan "a" untuk menambah ke akhir.
An algorithm 算法 is a clear list of steps that solves a problem. Decomposition 分解 means breaking a big problem into smaller parts you can solve one at a time.
Abstraction 抽象 means ignoring detail: you use largest(...) without re-reading how it works.
Bahasa Indonesia
Algoritma adalah daftar langkah yang jelas yang memecahkan masalah. Dekomposisi berarti memecah masalah besar menjadi bagian-bagian kecil yang dapat Anda selesaikan satu per satu.
# Algorithm: find the largest number in a list
def largest(nums):
best = nums[0]
for n in nums:
if n > best:
best = n
return best
print(largest([3, 9, 2, 7])) # 9
Abstraksi berarti mengabaikan detail: Anda menggunakan largest(...) tanpa membaca ulang cara kerjanya.
11.2
Pseudocode & flowchart
English
Pseudocode 伪代码 is plain, structured English for an algorithm, written before the real code. It is not run.
A flowchart 流程图 draws the same plan: a box for each step, a diamond for each decision 判断, and arrows for the order.
Bahasa Indonesia
Pseudocode adalah bahasa Inggris terstruktur sederhana untuk algoritma, ditulis sebelum kode nyata. Ini tidak dijalankan.
SET best TO first number
FOR Each number n
IF n > best
THEN
SET best TO n
OUTPUT best
Flowchart menggambar rencana yang sama: kotak untuk setiap langkah, belah ketupat untuk setiap keputusan, dan panah untuk urutan.
11.3
Rekursi & tumpukan pemanggilan
English
Recursion 递归 is when a function calls itself. It needs a base case 基准情形 (a simple input that returns at once) and a recursive case 递归情形 (it calls itself on a smaller input).
Each paused call sits on the call stack 调用栈 until the call above it returns.
Common mistakes
Recursion needs a base case, or it calls itself forever and crashes the call stack.
Pseudocode is for planning — it need not run, but every step must be unambiguous.
Break a big problem into small named steps before you write any code.
Bahasa Indonesia
Rekursi adalah ketika fungsi memanggil dirinya sendiri. Ia membutuhkan kasus dasar (input sederhana yang langsung mengembalikan) dan kasus rekursif (memanggil dirinya sendiri pada input yang lebih kecil).
Stack pemanggilan untuk factorial(3): setiap pemanggilan menunggu, lalu mengembalikan dalam urutan terbalik
def fact(n):
return 1 if n <= 1 else n * fact(n - 1)
print(fact(5)) # 120
Setiap pemanggilan yang tertahan berada di tumpukan pemanggilan hingga pemanggilan di atasnya mengembalikan.
Kesalahan umum
Rekursi memerlukan kasus dasar, atau ia akan memanggil dirinya sendiri selamanya dan membuat tumpukan pemanggilan crash.
Pseudocode untuk perencanaan — tidak perlu berjalan, tetapi setiap langkah harus tak ambigu.
Pecah masalah besar menjadi langkah-nama kecil sebelum menulis kode apa pun.
An abstract data type 抽象数据类型 (ADT) describes some data plus the operations on it, separate from how it is built. You use it through its operations, not through its inner storage.
Bahasa Indonesia
Tipe data abstrak (ADT) menggambarkan beberapa data beserta operasi di atasnya, terpisah dari bagaimana ia dibangun. Anda menggunakannya melalui operasinya, bukan melalui penyimpanan dalamnya.
# A stack ADT, built on a list
s = []
s.append(1) # add
s.append(2)
print(s.pop()) # 2 (remove the most recent)
12.2
Tumpukan (Stacks)
English
A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.
Bahasa Indonesia
Tumpukan adalah terakhir masuk, pertama keluar (LIFO). Anda push ke atas dan pop dari atas.
A stack removes from the top (LIFO); a queue removes from the front (FIFO)
stack = []
stack.append("a")
stack.append("b")
print(stack.pop()) # b
print(stack.pop()) # a
12.3
antrean (Queues)
English
A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.
Bahasa Indonesia
Antrean adalah pertama masuk, pertama keluar (FIFO). Anda enqueue di belakang dan dequeue dari depan.
queue = []
queue.append("a") # enqueue
queue.append("b")
print(queue.pop(0)) # a (dequeue the front)
print(queue.pop(0)) # b
12.4
Daftar terikat
English
A linked list 链表 is a chain of nodes 节点. Each node holds data and a pointer 指针 to the next node; the last points to None.
Bahasa Indonesia
Daftar linked adalah rantai node. Setiap node memegang data dan pointer ke node berikutnya; yang terakhir menunjuk ke None.
A linked list: each node holds data and a pointer to the next node, ending at None
n3 = {"data": 3, "next": None}
n2 = {"data": 2, "next": n3}
n1 = {"data": 1, "next": n2}
node = n1
while node is not None: # traverse to the end
print(node["data"])
node = node["next"]
# 1 2 3
12.5
Tabel hash
English
A hash table 哈希表 maps a key to a slot with a hash function 哈希函数. Two keys can land in the same slot — a collision 冲突. Python's dict is a hash table, so lookup is fast.
Bahasa Indonesia
Tabel hash memetakan kunci ke slot dengan fungsi hash. Dua kunci dapat mendarat di slot yang sama — tabrakan. dict Python adalah tabel hash, sehingga pencarian cepat.
Fungsi hash memetakan setiap kunci ke sebuah slot; dua kunci dapat bertabrakan di satu slot
A search 查找 finds where a value is. Linear search 线性查找 checks each item in turn, so it works on any list.
Binary search 二分查找 is much faster but needs a sorted list. It halves the range each step.
Bahasa Indonesia
Pencarian menemukan di mana suatu nilai berada. Pencarian linear memeriksa setiap item secara berurutan, sehingga bekerja pada daftar apa pun.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1 # not found
print(linear_search([4, 8, 2, 9], 2)) # 2
Pencarian biner jauh lebih cepat tetapi membutuhkan daftar terurut. Ia membagi dua jangkauan setiap langkah.
def binary_search(items, target):
lo, hi = 0, len(items) - 1
while lo <= hi:
mid = (lo + hi) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
Pencarian biner membagi dua jangkauan setiap langkah — O(log n) pada daftar terurut
13.2
Pengurutan (bubble & insertion)
English
To sort 排序 is to put items in order. Bubble sort 冒泡排序 repeatedly swaps 交换 neighbours that are in the wrong order.
Insertion sort 插入排序 builds a sorted part one item at a time, sliding each new item back into its place:
In real code, use Python's built-in sorted():
Bahasa Indonesia
Mengurutkan berarti menyusun item dalam urutan. Bubble sort berulang kali menukar tetangga yang urutannya salah.
def bubble_sort(a):
a = a[:] # work on a copy
for i in range(len(a)):
for j in range(len(a) - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
return a
print(bubble_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
Insertion sort membangun bagian terurut satu item sekaligus, menggeser setiap item baru kembali ke tempatnya:
def insertion_sort(a):
a = a[:] # work on a copy
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key: # shift bigger values right
a[j + 1] = a[j]
j -= 1
a[j + 1] = key # drop key into the gap
return a
print(insertion_sort([5, 2, 4, 1])) # [1, 2, 4, 5]
Dalam kode nyata, gunakan built-in Python sorted():
print(sorted([5, 2, 4, 1])) # [1, 2, 4, 5]
13.3
Efisiensi algoritmik
English
Efficiency 效率 asks how the work grows as the input grows. We describe it with Big-O 大O记号.
Big-O
Name
Example
$O(1)$
constant
look up a dict key
$O(\log n)$
logarithmic
binary search
$O(n)$
linear
linear search
$O(n^2)$
quadratic
bubble sort
Bahasa Indonesia
Efisiensi menanyakan bagaimana beban kerja bertambah seiring input bertambah. Kita mendeskripsikannya dengan Big-OO.
Bagaimana jumlah langkah bertambah seiring ukuran input untuk kompleksitas umum
Big-O
Nama
Contoh
$O(1)$
konstan
melihat kunci dict
$O(\log n)$
logaritmik
pencarian biner
$O(n)$
linear
pencarian linear
$O(n^2)$
kuadratik
bubble sort
def steps(n): # how many steps a linear scan takes
count = 0
for i in range(n):
count = count + 1
return count
print(steps(100)) # 100 -> O(n)
13.4
Keacakan & simulasi
English
The random module makes random numbers. Use a seed 种子 to make results repeatable. A simulation 模拟 runs many random trials to estimate an answer.
Common mistakes
Binary search only works on a sorted list.
Big-O tells you how the time GROWS, not the exact time; an O(n²) method beats O(n) only for tiny inputs.
Bubble sort is O(n²) — fine for learning, but slow on large lists.
Bahasa Indonesia
Modul random menghasilkan angka acak. Gunakan seed agar hasil dapat direproduksi. Simulasi menjalankan banyak percobaan acak untuk memperkirakan jawaban.
import random
random.seed(0)
rolls = [random.randint(1, 6) for _ in range(1000)]
print(rolls.count(6)) # about 1/6 of 1000
Kesalahan umum
Pencarian biner hanya bekerja pada daftar terurut.
Big-O memberi tahu Anda bagaimana waktu BERKEMBANG, bukan waktu eksak; metode O(n²) mengalahkan O(n) hanya untuk input sangat kecil.
Bubble sort adalah O(n²) — cukup untuk belajar, tetapi lambat pada daftar besar.
A class 类 is a blueprint. An object 对象 is one thing built from it (an instance 实例). __init__ is the constructor 构造方法 that sets up each object; self is the object itself.
name is an attribute 属性 (data on the object); speak is a method 方法 (an action).
Add __str__ to control what print(obj) shows:
Bahasa Indonesia
Kelas adalah cetak biru. Objek adalah satu hal yang dibangun darinya (instans). __init__ adalah konstruktor yang menyiapkan setiap objek; self adalah objek itu sendiri.
class Dog:
def __init__(self, name):
self.name = name # an attribute
def speak(self):
return self.name + " says woof"
d = Dog("Rex")
print(d.speak()) # Rex says woof
name adalah atribut (data pada objek); speak adalah method (tindakan).
Tambahkan __str__ untuk mengontrol apa yang print(obj) tampilkan:
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Dog named {self.name}"
print(Dog("Rex")) # Dog named Rex
Kelas adalah cetak biru; memanggilnya membuat objek
14.2
Warisan, enkapsulasi & polimorfisme
English
Inheritance 继承 lets a subclass 子类 reuse a superclass 父类. Use super() to call the parent; override 重写 a method to change it.
Encapsulation 封装 hides data behind methods; a leading underscore marks it private 私有.
Polymorphism 多态 means one name, many behaviours — the right speak runs for each object.
Bahasa Indonesia
Warisan memungkinkan subclass menggunakan ulang superclass. Gunakan super() untuk memanggil induk; atur ulang method untuk mengubahnya.
class Animal:
def speak(self):
return "some sound"
class Cat(Animal):
def speak(self): # override
return "meow"
print(Cat().speak()) # meow
Enkapsulation menyembunyikan data di balik method; garis bawah di awal menandainya sebagai privat.
class Account:
def __init__(self):
self._balance = 0 # private
def deposit(self, n):
self._balance += n
def balance(self):
return self._balance
a = Account()
a.deposit(50)
print(a.balance()) # 50
Polimorfisme berarti satu nama, banyak perilaku — speak yang tepat berjalan untuk setiap objek.
class Cat:
def speak(self):
return "meow"
class Cow:
def speak(self):
return "moo"
for animal in [Cat(), Cow()]:
print(animal.speak()) # meow, then moo
14.3
Paradigma pemrograman
English
A paradigm 范式 is a style of writing programs. Procedural 过程式 code is a sequence of steps and functions. Object-oriented 面向对象 code groups data and methods into objects. Declarative 声明式 code says what you want, not how (a list comprehension or SQL).
Common mistakes
Every method needs self as its first parameter.
__init__ sets up a new object and runs automatically when you create one.
Two objects of the same class have separate attributes; changing one does not change the other.
Bahasa Indonesia
Paradigma adalah gaya menulis program. Kode prosedural adalah urutan langkah dan fungsi. Kode berorientasi objek mengelompokkan data dan method menjadi objek. Kode deklaratif menyatakan apa yang Anda inginkan, bukan bagaimana (list comprehension atau SQL).
def total(nums): # procedural
t = 0
for n in nums:
t += n
return t
print(total([1, 2, 3])) # 6
print(sum([1, 2, 3])) # 6 (declarative: same result)
Kesalahan umum
Setiap method memerlukan self sebagai parameter pertamanya.
__init__ mengatur objek baru dan berjalan otomatis saat Anda membuat satu.
Dua objek dari kelas yang sama memiliki atribut terpisah; mengubah satu tidak mengubah yang lain.
A bit 比特 is a single 0 or 1. Binary 二进制 is the base-2 number system: each place is worth twice the one to its right (1, 2, 4, 8, …). Denary 十进制 (base-10) is our normal numbers.
8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.
Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:
Bahasa Indonesia
Bit adalah satu 0 atau 1 tunggal. Biner adalah sistem bilian basis-2: setiap posisi bernilai dua kali lipat dari posisi di sebelah kanannya (1, 2, 4, 8, …). Desimal (basis-10) adalah angka kita sehari-hari.
Compression 压缩 makes data smaller. Lossless 无损 compression keeps every bit, so you rebuild the original exactly. Lossy 有损 compression throws away detail — smaller but not exact — and is used for photos and music.
Run-length encoding 游程编码 is a simple lossless method: store a run 游程 (a repeat) as a count plus the value.
Common mistakes
n bits store 2**n different values, from 0 up to 2**n - 1.
Lossy compression throws away detail and cannot be undone; lossless can be reversed exactly.
Bahasa Indonesia
Kompresi membuat data lebih kecil. Kompresi lossless menjaga setiap bit, sehingga Anda dapat merekonstruksi aslinya persis. Kompresi lossy membuang detail — lebih kecil tapi tidak persis — dan digunakan untuk foto dan musik.
Pengkodean run-length adalah metode lossless sederhana: simpan rentang (pengulangan) sebagai count ditambah nilainya.
def rle(text):
out = ""
i = 0
while i < len(text):
run = 1
while i + run < len(text) and text[i + run] == text[i]:
run += 1
out += str(run) + text[i]
i += run
return out
print(rle("AAAABBBCCD")) # 4A3B2C1D
Kesalahan umum
n bits menyimpan 2**n nilai berbeda, dari 0 hingga 2**n - 1.
Kompresi lossy membuang detail dan tidak dapat dibalik; lossless dapat dikembalikan persis.
Computing 计算 means solving problems with computers: input, process, output. Good software is built in a design cycle 设计循环 — plan, write, test, improve — repeated many times.
Break a problem down, build a small part, test it, then add more.
Programmers work in teams and reuse each other's code.
Bahasa Indonesia
Komputasi berarti menyelesaikan masalah dengan komputer: input, proses, output. Perangkat lunak baik dibangun dalam siklus desain — rencanakan, tulis, uji, perbaiki — diulang berkali-kali.
Pecah masalah, bangun sebagian kecil, uji, lalu tambahkan lagi.
Programmer bekerja dalam tim dan menggunakan ulang kode orang lain.
16.2
Internet
English
The Internet 互联网 is a network 网络 of networks. Data is split into packets 数据包 that travel separately and are put back together at the other end. Shared rules called protocols 协议 (such as TCP/IP) make this work. If one path breaks, packets take another route — this is redundancy 冗余, which gives fault tolerance 容错.
Layer
Job
HTTP
request and send web pages
TCP
reliable delivery, in order
IP
addressing and routing
Bahasa Indonesia
Internet adalah jaringan dari jaringan. Data dibagi menjadi paket yang traveling secara terpisah dan digabungkan kembali di ujung lain. Aturan bersama yang disebut protokol (seperti TCP/IP)使它工作。 Jika satu jalur rusak, paket mengambil rute lain — ini redundansi, yang memberikan toleransi kesalahan.
Peta Internet: setiap garis adalah jalur antara dua jaringan
Lapisan
Tugas
HTTP
permintaan dan kirim halaman web
TCP
pengiriman andal, berurutan
IP
pengalamatan dan perutean
16.3
Komputasi paralel & terdistribusi
English
Sequential 顺序 code does one step at a time. Parallel 并行 computing does several steps at once on many cores 核心, which can give a speedup 加速. Distributed 分布式 computing spreads the work across many computers, such as a cloud.
Not everything can run in parallel: some steps must wait for an earlier result.
Bahasa Indonesia
Kode sekuensial melakukan satu langkah pada satu waktu. Komputasi paralel melakukan beberapa langkah sekaligus di banyak inti prosesor, yang dapat memberikan percepatan. Komputasi terdistribusi menyebarkan tugas ke banyak komputer, seperti di cloud.
Tidak semua hal dapat berjalan secara paralel: beberapa langkah harus menunggu hasil sebelumnya.
16.4
Dampak komputasi
English
Computing brings both benefits and harms. The digital divide 数字鸿沟 means not everyone has equal access to it. Software can carry bias 偏见 from the data it learns from. Respect intellectual property 知识产权 (licences), and protect people's personal data 个人数据 and privacy 隐私.
Common mistakes
The Internet and the World Wide Web are not the same: the Web is one service that runs on top of the Internet.
More processor cores help only if the work can be split into parts that run at the same time.
Bahasa Indonesia
Komputasi membawa manfaat dan kerugian. Kesenjangan digital berarti tidak semua orang memiliki akses yang setara. Perangkat lunak dapat membawa bias dari data yang dipelajari. Hormati hak kekayaan intelektual (lisensi), dan lindungi data pribadi serta privasi orang.
Kesalahan umum
Internet dan World Wide Web bukan hal yang sama: Web adalah satu layanan yang berjalan di atas Internet.
Inti prosesor lebih banyak hanya membantu jika pekerjaan dapat dibagi menjadi bagian yang dijalankan bersamaan.
A mini-project 小项目 combines earlier ideas: data in a list, a function with selection inside a loop, and printed output. This is also the shape of the AP Create Performance Task.
Project: average mark
Project: count passes
Project: filter to a new list
The AP Create Task wants a list, a parameterised procedure 过程 that uses selection 选择 and iteration 迭代, and some input/output. Each project above is exactly that shape — build small pieces, then join them.
Common mistakes
Build in small steps and test each part before moving on — do not write it all at once.
Read the whole task first, then plan the input → process → output before you code.
Bahasa Indonesia
Proyek mini menggabungkan ide-ide sebelumnya: data dalam daftar, fungsi dengan seleksi di dalam perulangan, dan output tercetak. Ini juga merupakan bentuk dari Tugas Kinerja AP Create.
def count_passes(marks, pass_mark=60):
passes = 0
for m in marks: # iteration
if m >= pass_mark: # selection
passes += 1
return passes
print(count_passes([88, 50, 95, 60])) # 3
Proyek: filter ke daftar baru
def merit(marks):
return [m for m in marks if m >= 80]
print(merit([88, 71, 95, 60])) # [88, 95]
Tugas AP Create meminta sebuah daftar, prosedur berparameter yang menggunakan seleksi dan iterasi, serta input/output. Setiap proyek di atas memiliki bentuk persis itu — bangun potongan kecil, lalu gabungkan.
Kesalahan umum
Bangun dalam langkah-langkah kecil dan uji setiap bagian sebelum melanjutkan — jangan tulis semuanya sekaligus.
Baca seluruh tugas terlebih dahulu, lalu rencanakan alur input → proses → output sebelum memprogram.
Pick one and the site follows you — notes, papers, videos and practice all open on it. · Pilih satu dan situs mengikuti Anda — catatan, kertas, video, dan latihan semua terbuka di sana.
Type to search notes, lessons, code, vocabulary and past-paper questions across every subject. · Ketik untuk mencari catatan, pelajaran, kode, kosakata, dan pertanyaan soal lama di setiap mata pelajaran.