Skip to content · ⁨コンテンツへスキップ⁩
Subjects · ⁨科目⁩
  • 1 Getting started · ⁨はじめに⁩
    1.1

    最初のプログラム

    English

    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.
    日本語

    ソースコードはインタープリタを経て出力を生成します

    print() 関数は画面にテキストを表示します。これを出力(アウトプット)と呼びます。引用符内のテキストは文字列です。

    print("Hello, world!")
    print("I am learning Python")
    
    • 各print()は新しい行を開始する。
    • 引用符は "double" または 'single' のどちらでも構いません — どちらも文字列を作ります。
    • プログラムを実行するまでは何もしません。
    ソースコードがインタープリターを通じて通って出力を生成します
    ソースコードがインタープリターを通じて通って出力を生成します
    1.2

    コメントとコードスタイル

    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 错误.
    日本語

    コメントは # で始まります。Python はその行の # の後のすべてのものを無視します。コメントは他の人がコードを理解するためにあり、コードの動作自体を変えるものではありません。

    # This line is a note for humans
    print("Hi")        # you can also comment at the end of a line
    

    良いスタイルはコードを読みやすくします:

    • 値の意味を明確に示す名前を使用する。
    • 各文は1行ずつにする。
    • 通常の行の先頭にスペースを入れない。Pythonでは、先頭のスペース(インデント)には特別な意味があるため、誤ったスペースがエラーとなる。
    1.3

    入力、処理、出力

    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.
    日本語

    多くのプログラムは単純な手順に従う:入力 → 処理 → 出力。データを取得し、それに対して何らかの操作を行い、結果を表示する。

    input()関数はユーザーが入力したテキストを読み込む。常に文字列を返す。

    name = input("What is your name? ")
    print("Hello, " + name)
    
    • input()はユーザーが入力してエンターキーを押すのを待つ。
    • 入力を変数に格納しておき、後で利用できるようにする。
    • input()は文字列を返すので、数値が必要な場合はまずint(...)で変換する。

    ** 一般的なミス **

    • 引用符の忘れ:print(Hello)はHelloという名の変数を検索しようとしてNameErrorを起こす。テキストには引用符が必要:print("Hello")。
    • 行の先頭にある余分なスペース:Pythonはインデントを構造とみなすため、IndentationErrorを起こす。
    • input()が数値を返すと仮定している。常に文字列を返すので、計算を行う前にint(...)で包む。
  • 2 Variables, types & operators · ⁨変数、型、演算子⁩
    2.1

    変数と代入

    English

    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).
    日本語

    変数は値に対する名前のことである。=を使って作成し、これを代入と呼ぶ。左側に名前、右側に値を書く。

    age = 17
    name = "Mei"
    price = 9.99
    print(age, name, price)
    

    今 age は 17 を保持しています。値が必要などこでもこの名前を使用し、後で変更できます:

    age = 17
    age = age + 1   # age is now 18
    print(age)
    
    変数は格納された値に紐付けられた名前である
    各変数名はメモリ上の値を指し示す
    • =記号は「等しい」ではない。「左側の名の下に右側を格納する」ことを意味する。
    • 2つの値が等しいかどうかテストするには、==を使う(以下参照)。
    2.2

    数値: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.
    日本語

    Pythonには2つの主要な数値型がある。整数(int)は17のような全体数である。浮動小数点数(float)は9.99のような小数点を持つ。

    これらの演算子は数値上で動作する:

    演算子 意味 例 結果
    + 加算 3 + 2 5
    - 減算 3 - 2 1
    * 乗算 3 * 2 6
    / 除算(常にfloat) 7 / 2 3.5
    // 整数除算 7 // 2 3
    % 剰余(モジュロ) 7 % 2 1
    ** べき乗 2 ** 3 8
    • /は常にfloatを返すので、4 / 2は2.0である。
    • //と%はセットで使われる:17 // 5は3であり、17 % 5は2である。
    2.3

    式と型変換

    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).
    日本語

    式とは値を持つもののことであり、3 + 4 * 2のようなものがある。Pythonは通常の数学的な優先順位(*と/が+と-より先)を用いる;順序を明確にするために括弧を入れる。

    input()は文字列を返すので、計算する前に変換する。ある型から別の型へ値を変えることを型変換と呼ぶ:

    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")は失敗するため、数字のように見えるテキストのみを変換する。
    • 異なる型の混在も失敗する:"age: " + 17はエラーです;"age: " + str(17)と書く。
    2.4

    ブール値と比較

    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.
    日本語

    ブール値は2つの値のいずれか:TrueまたはFalse。比較演算の結果はブール値を返す。

    演算子 意味
    == 等しい
    != 等しくない
    < > 未満 / 超える
    <= >= 以下 / 以上
    print(7 > 2)        # True
    print(3 == 3.0)     # True
    age = 20
    print(age >= 18)    # True
    

    and、or、notで比較を結合する:

    age = 20
    print(age >= 13 and age <= 19)   # True only for a teenager
    

    ** 一般的なミス **

    • /は常にfloatを返す。4 / 2が2.0であっても同様である。全体数が欲しい場合は//を使う。
    • =の代わりに==を使う:=は値を割り当て、==は2つの値が等しいかをテストする。
    • テキストと数値を結合する:"age: " + 5はTypeErrorを起こす。str(5)で変換してから行う。
    • 浮動小数点数は正確ではないため、0.1 + 0.2は0.3と厳密に等しくなく、floatの結果に対して==を使うのは避けるべきである。
  • 3 Strings · ⁨文字列⁩
    3.1

    Indexing

    English

    A string 字符串 is text inside quotes. Each character 字符 has a position, called its index 索引. The first index is 0, not 1.

    Read one character with square brackets:

    • Counting starts at 0, so the last index is len(word) - 1.
    • A negative index counts back from the end: word[-1] is the last character.
    • An index that is too large gives an error 错误 (an IndexError).
    日本語

    A string 字符串 is text inside quotes. Each character 字符 has a position, called its index 索引. The first index is 0, not 1.

    Read one character with square brackets:

    word = "Python"
    print(word[0])    # P  (the first character)
    print(word[2])    # t
    print(len(word))  # 6  (how many characters)
    
    • Counting starts at 0, so the last index is len(word) - 1.
    • A negative index counts back from the end: word[-1] is the last character.
    word = "Python"
    print(word[-1])   # n
    print(word[-2])   # o
    
    • An index that is too large gives an error 错误 (an IndexError).
    s[start:stop] is a half-open window of characters
    s[start:stop] is a half-open window of characters
    3.2

    Slicing

    English

    A slice 切片 takes a part of a string. Write word[start:end]. The slice keeps start but stops before end.

    • Leave out start to begin at 0; leave out end to go to the end.
    • A third number is the step 步长. word[::-1] reverses 反转 the string.
    日本語

    A slice 切片 takes a part of a string. Write word[start:end]. The slice keeps start but stops before end.

    word = "Python"
    print(word[0:3])   # Pyt   (positions 0, 1, 2)
    print(word[2:5])   # tho
    
    • Leave out start to begin at 0; leave out end to go to the end.
    word = "Python"
    print(word[:3])    # Pyt
    print(word[3:])    # hon
    
    • A third number is the step 步长. word[::-1] reverses 反转 the string.
    print("Python"[::-1])   # nohtyP
    
    3.3

    String methods & length

    English

    A method 方法 is a function that belongs to a value. You call it with a dot:

    Strings are immutable 不可变: a method returns a new string and never changes the original 原始 one.

    Common methods (each returns a new value):

    Method Meaning Example Result
    .upper() / .lower() change case "Hi".lower() hi
    .strip() remove edge spaces " hi ".strip() hi
    .replace(a, b) swap text "cat".replace("c", "b") bat
    .split(sep) break into a list "a,b".split(",") ['a', 'b']

    Join strings with +. This is called concatenation 拼接:

    日本語

    A method 方法 is a function that belongs to a value. You call it with a dot:

    name = "mei chen"
    print(name.upper())     # MEI CHEN
    print(name.title())     # Mei Chen
    print(len(name))        # 8
    

    Strings are immutable 不可变: a method returns a new string and never changes the original 原始 one.

    name = "mei"
    print(name.upper())     # MEI  (the returned value)
    print(name)             # mei  (the original is unchanged)
    

    Common methods (each returns a new value):

    Method Meaning Example Result
    .upper() / .lower() change case "Hi".lower() hi
    .strip() remove edge spaces " hi ".strip() hi
    .replace(a, b) swap text "cat".replace("c", "b") bat
    .split(sep) break into a list "a,b".split(",") ['a', 'b']

    Join strings with +. This is called concatenation 拼接:

    first = "Mei"
    last = "Chen"
    print(first + " " + last)   # Mei Chen
    
    3.4

    f-strings

    English

    An f-string 格式化字符串 builds text from values. Put f before the quote, then write {...} around a value.

    • Any expression 表达式 can go inside the braces.
    • {value:.2f} rounds to 2 decimal places 小数位.

    Common mistakes

    • Strings cannot be changed in place: s[0] = "x" raises an error. Build a new string instead.
    • Indexing starts at 0; the last character is s[-1], and s[len(s)] is out of range.
    • A slice s[a:b] includes a but stops before b.
    • String methods return a NEW string: s.upper() does nothing unless you store the result.
    日本語

    An f-string 格式化字符串 builds text from values. Put f before the quote, then write {...} around a value.

    name = "Mei"
    age = 17
    print(f"{name} is {age} years old")   # Mei is 17 years old
    
    • Any expression 表达式 can go inside the braces.
    • {value:.2f} rounds to 2 decimal places 小数位.
    price = 9.5
    print(f"Two cost {price * 2}")        # Two cost 19.0
    print(f"Pi is about {3.14159:.2f}")   # Pi is about 3.14
    

    Common mistakes

    • Strings cannot be changed in place: s[0] = "x" raises an error. Build a new string instead.
    • Indexing starts at 0; the last character is s[-1], and s[len(s)] is out of range.
    • A slice s[a:b] includes a but stops before b.
    • String methods return a NEW string: s.upper() does nothing unless you store the result.
  • 4 Selection · ⁨選択構造⁩
    4.1

    if / elif / else

    English

    A program chooses what to do with if. It runs an indented 缩进 block only when a condition 条件 is true. The if line ends with a colon 冒号.

    Add elif (else-if) for more cases and else for "anything else". Python runs the first true branch 分支 only, then skips the rest.

    • Compare values with == (equal to), != (not equal to), <, >, <=, >=.
    • A comparison 比较 gives a Boolean 布尔值 — either True or False.
    日本語

    プログラムはifに何をさせるかを選択します。条件が真である場合にのみ、インデントされたブロックを実行します。if行はコロンで終わります。

    score = 72
    if score >= 60:
        print("pass")
    # pass
    

    追加のケースにはelif (elif) を、「それ以外」の場合にはelse を使用します。Python は最初の真の分岐のみを実行し、残りをスキップします。

    score = 72
    if score >= 80:
        print("A")
    elif score >= 60:
        print("B")
    else:
        print("fail")
    # B
    
    • 値を比較するには、== (等しい)、!= (等しくない)、<、>、<=、>= を使用します。
    • 比較演算の結果はブール値であり、その値はTrue かFalse のどちらかです。
    if / elif / else: 一つの分岐のみが実行される
    if / elif / else: 一つの分岐のみが実行される
    4.2

    条件の組み合わせ

    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.
    日本語

    条件をand、or、not で結合します。and は両方の側が真である必要があります;or は片方でも真であれば十分です;not はブール値を反転させます。

    age = 16
    has_ticket = True
    if age >= 18 and has_ticket:
        print("entry allowed")
    else:
        print("entry refused")
    # entry refused
    
    • 優先順位を明確にするために括弧を使用します:(a or b) and c 。
    temp = 30
    if temp > 25 and not temp > 35:
        print("warm but ok")
    # warm but ok
    

    ** 一般的なミス **

    • elif を書き、else if とは書かないでください。
    • if / elif / else の各行はコロン : で終わり、その本文はインデントする必要がある。
    • if x = 5: はエラーです — 比較するには== を使用してください。
    • else は条件を受け取らず、if とelif のみが条件を受け取ります。
  • 5 Iteration · ⁨反復構造⁩
    5.1

    forループとrange

    English

    A loop 循环 repeats code. A for loop repeats once for each item in a sequence 序列. range(n) gives the numbers 0 up to n - 1.

    • range(a, b) goes from a up to (but not including) b.
    • range(a, b, step) adds a step 步长 each time.
    日本語

    ループはコードを繰り返します。for ループはシーケンス内の各アイテムに対して一度だけ繰り返します。range(n) は0 からn - 1 までの数字を生成します。

    for i in range(5):
        print(i)
    # 0, then 1, 2, 3, 4 (each on its own line)
    
    • range(a, b) はa からb (ただし含まない)まで進みます。
    • range(a, b, step) は毎回ステップを追加します。
    for n in range(2, 11, 2):
        print(n)        # 2 4 6 8 10
    
    for i in range(n): body runs with i = 0 … n-1
    for i in range(n): body runs with i = 0 … n-1
    5.2

    アキュムレーターパターン

    English

    To build a result across a loop, start a variable before the loop, then update 更新 it each turn. This is the accumulator 累加器 pattern.

    • The same idea counts how many items match a test.
    日本語

    ループを通じて結果を構築するには、ループの前に変数を初期化し、その後各ターンで更新します。これがアキュムレーターパターンです。

    total = 0
    for n in range(1, 6):
        total = total + n
    print(total)        # 15
    
    • 同じ考え方は、テストに一致するアイテムの個数を数えるのに使えます。
    count = 0
    for letter in "banana":
        if letter == "a":
            count = count + 1
    print(count)        # 3
    
    5.3

    while ループ

    English

    A while loop repeats as long as a condition stays true. Change something inside, or it never stops — an infinite loop 无限循环.

    • break leaves the loop straight away.
    日本語

    while ループは条件が真である限り繰り返されます。内部で何かを変えない場合、止まらずに無限ループになります。

    n = 1
    while n <= 3:
        print(n)
        n = n + 1
    # 1 2 3
    
    • break はループから即座に脱出します。
    total = 0
    while True:
        total = total + 10
        if total >= 30:
            break
    print(total)        # 30
    
    5.4

    ネストループ

    English

    A loop inside another loop is a nested loop 嵌套循环. The inner loop 内层循环 runs fully for each turn of the outer loop 外层循环.

    Common mistakes

    • range(n) goes from 0 to n - 1, not 1 to n — the classic off-by-one error.
    • Changing a list while looping over it skips items; loop over a copy if you must remove things.
    • Forgetting to change the loop variable in a while makes it run forever.
    • Indentation decides what is inside the loop; a wrongly-indented line runs only once, after the loop.
    日本語

    ループ内のループはネストループと呼ばれます。内側のループは外側のループの各ターンに対して完全に実行されます。

    for row in range(3):
        line = ""
        for col in range(3):
            line = line + "*"
        print(line)
    # ***
    # ***
    # ***
    

    ** 一般的なミス **

    • range(n) は0 からn - 1 まで進み、1 からn までではありません — 典型的なオフバイワンエラーです。
    • ループ中にリストを変更するとアイテムがスキップされ、削除する必要がある場合はコピーをループしてください。
    • while のループ変数を変更しないことを忘れると、永遠に実行されます。
    • インデントがループ内の内容を決定します。誤ったインデントの行はループ後に一度だけ実行されます。
  • 6 Lists & 2-D lists · ⁨リストと2次元リスト⁩
    6.1

    リスト

    English

    A list 列表 holds many values in order, inside []. Each item 元素 has an index (from 0).

    • Change an item by its index: scores[1] = 100.
    • A list can grow and shrink; a string cannot.

    The everyday list tools:

    Tool Does
    a.append(x) adds x at the end
    a.insert(i, x) inserts x at position i
    a.remove(x) removes the first x
    a.pop() / a.pop(i) removes and returns the last item / item i
    a.sort() sorts the list in place
    sorted(a) returns a NEW sorted list
    x in a is x in the list?
    len(a), sum(a), max(a), min(a) size and quick maths
    日本語

    リストは[] 内に順序を持って多くの値を保持します。各アイテムにはインデックス(0 から)があります。

    scores = [88, 71, 95]
    print(scores[0])      # 88
    print(len(scores))    # 3
    scores.append(60)     # add to the end
    print(scores)         # [88, 71, 95, 60]
    
    • インデックスを使用してアイテムを変更します:scores[1] = 100 。
    • リストは成長・縮小できますが、文字列はできません。

    一般的なリストツール:

    ツール 機能
    a.append(x) x を末尾に追加
    a.insert(i, x) x を位置i に挿入
    a.remove(x) 最初のx を削除
    a.pop() / a.pop(i) 最後のアイテム / アイテムi を削除して返す
    a.sort() リストをインプレースでソート
    sorted(a) 新しいソート済みリストを返す
    x in a ⟨x⟩ がリストに含まれていますか?
    len(a), sum(a), max(a), min(a) サイズと簡易計算
    List indices start at 0
    List indices start at 0
    6.2

    リストの走査

    English

    To traverse 遍历 a list is to visit each item. A for loop does this with no index needed.

    • Use enumerate when you also need the index.
    日本語

    リストを走査することは各アイテムを訪問することです。for ループはインデックスなしで行います。

    scores = [88, 71, 95]
    total = 0
    for s in scores:
        total = total + s
    print(total)          # 254
    
    • インデックスも必要な場合にenumerate を使用します。
    for i, name in enumerate(["a", "b"]):
        print(i, name)    # 0 a  /  1 b
    
    6.3

    2次元リスト(グリッド)

    English

    A 2-D list 二维列表 is a list of lists — a grid 网格 of rows and columns. Use two indexes: grid[row][col].

    • A nested loop 嵌套循环 visits every cell.
    日本語

    2次元リストはリストのリストであり、行と列のグリッドです。2つのインデックスを使用します:grid[row][col] 。

    grid = [[1, 2, 3],
            [4, 5, 6]]
    print(grid[0][2])     # 3
    print(grid[1][0])     # 4
    
    • ネストループはすべてのセルを訪問します。
    grid = [[1, 2], [3, 4]]
    for row in grid:
        for value in row:
            print(value, end=" ")
    print()               # 1 2 3 4
    
    6.4

    リスト圧縮

    English

    A list comprehension 列表推导式 builds a new list in one line: [expression for item in sequence].

    • Add if to keep only some items.
    日本語

    リスト圧縮は1行で新しいリストを構築します:[expression for item in sequence] 。

    squares = [x * x for x in range(5)]
    print(squares)        # [0, 1, 4, 9, 16]
    
    • if を追加して、特定の項目のみを保持する。
    evens = [n for n in range(10) if n % 2 == 0]
    print(evens)          # [0, 2, 4, 6, 8]
    
    6.5

    タプル & セット

    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].
    日本語

    タプルは丸括弧内の固定シーケンスです。作成後に変更できません — 一緒に扱う値に使用し、名前にアンパッキングしてください。

    point = (3, 4)
    x, y = point            # unpacking
    print(x, y)             # 3 4
    

    2つの結果を返す必要がある関数はタプルを返します:

    def min_max(nums):
        return min(nums), max(nums)
    
    lo, hi = min_max([5, 2, 9])
    print(lo, hi)           # 2 9
    

    セットは各値を一度ずつ、順序なく格納します。重複の除去や高速な所属テストに最適です。

    votes = ["red", "blue", "red", "green", "red"]
    colours = set(votes)
    print(len(colours))         # 3  (duplicates removed)
    print("blue" in colours)    # True
    

    ** 一般的なミス **

    • b = a はリストをコピーしません:両方の名前は同じリストを指しているため、一方を変更すると他も変化します。a.copy() またはa[:] を使用してください。
    • 最後のアイテムはa[-1] で、a[len(a)] は範囲外です。
    • append は1つのアイテムのみを追加します。別のリストを結合するにはextend または+ を使用してください。
    • [[0]*3]*3 でグリッドを構築すると、同一の行の3つのコピーを作成してしまいます。代わりにループ内で行を構築してください。
    • アイテムが1つのタプルにはコンマが必要です:(5,) 、(5) とは書かないでください。
    • セットには順序がなく重複もないため、s[0] でインデックスすることはできません。
  • 7 Dictionaries · ⁨辞書(Dictionaries)⁩
    7.1

    ディクショナリ

    English

    A dictionary 字典 (dict) stores key 键 → value 值 pairs. You look up a value by its key, not by a number index.

    Add and update

    Assign to a key to add it, or to change an existing one.

    Check and loop

    Use in to test for a key. Loop over the keys, or over .items() to get both key and value.

    • .get(key, default) returns a default 默认值 when the key is missing — no error.

    The classic exam pattern — tally how often each value appears:

    • .get(letter, 0) supplies 0 the first time a key is seen, so there is no KeyError.

    Common mistakes

    • Reading a missing key with d[key] raises a KeyError; use d.get(key) or test if key in d first.
    • Assigning d[key] again overwrites the old value — keys are unique.
    • Keys must be immutable, such as a string or number — a list cannot be a key.
    日本語

    ディクショナリ(dict )はキー→値のペアを格納します。数値インデックスではなくキーで値を検索します。

    student = {"name": "Mei", "score": 88}
    print(student["name"])     # Mei
    print(student["score"])    # 88
    

    追加と更新

    キーに割り当てて追加するか、既存のものを更新します。

    student = {"name": "Mei"}
    student["score"] = 88      # add a new key
    student["score"] = 90      # update the value
    print(student)             # {'name': 'Mei', 'score': 90}
    

    確認とループ

    キーの存在をテストするにはin を使用します。キーをループするか、.items() をループしてキーと値の両方を取得します。

    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) はキーが存在しない場合にデフォルトを返すので、エラーになりません。
    student = {"name": "Mei"}
    print(student.get("age", 0))   # 0
    

    典型試験パターン — 各値が出現した回数をカウントします:

    word = "banana"
    counts = {}
    for letter in word:
        counts[letter] = counts.get(letter, 0) + 1
    print(counts)   # {'b': 1, 'a': 3, 'n': 2}
    
    • .get(letter, 0) はキーが初めて見た時に0 を提供するため、KeyErrorになりません。

    ** 一般的なミス **

    • d[key] で欠落しているキーを読むとKeyErrorが発生します;d.get(key) を使用するか、先にif key in d をテストしてください。
    • d[key] を再度割り当てると古い値が上書きされます — キーは一意です。
    • キーは不変型である必要があり、文字列や数値などです — リストはキーになれません。
    A dictionary maps each key to one value
    A dictionary maps each key to one value
  • 8 Functions & abstraction · ⁨関数と抽象化⁩
    8.1

    関数の定義と呼び出し

    English

    A function 函数 is a named block of code you can reuse. Define 定义 it with def, then call 调用 it by name.

    • The code inside runs only when you call the function.
    日本語

    関数は再利用可能な名付けられたコードブロックです。def で定義し、名前を指定して呼び出します。

    def greet():
        print("Hello!")
    
    greet()        # Hello!
    greet()        # Hello!
    
    • 関数を呼び出した時だけに内部のコードが実行されます。
    def defines; call runs; return sends a value back
    def は定義します; call は呼び出します; return は値を戻します
    8.2

    返り値

    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.
    日本語

    関数は return を使って値を返すことができます。then(その結果)はその値を表します。

    def square(n):
        return n * n
    
    print(square(5))          # 25
    print(square(3) + 1)      # 10
    
    • return は関数を即座に終了させます。return を持たない関数は None を返します。
    8.3

    パラメータ、引数 & スコープ

    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:

    日本語

    パラメータは def 内の名前です。引数は渡す値です。

    def power(base, exp):         # base, exp are parameters
        return base ** exp
    
    print(power(2, 3))            # 8  (2 and 3 are arguments)
    

    関数内で作成された変数はローカルです — そこでのみ存在します。その領域がスコープです。

    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
    

    パラメータにはデフォルト値を設定でき、呼び出し側で省略した際に使われます:

    def greet(name, greeting="Hello"):
        return greeting + ", " + name
    
    print(greet("Mei"))              # Hello, Mei
    print(greet("Sam", "Welcome"))   # Welcome, Sam
    
    8.4

    手続的抽象

    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.
    日本語

    手続的抽象とは、名前 behind に詳細を隠すことです。関数はその名前と役割を使って使い、内部の仕組みではなく使います。

    def area_of_rectangle(w, h):
        return w * h
    
    print(area_of_rectangle(4, 5))   # 20
    
    • 良い関数は一つのタスクだけを行い、明確な名前を持ち、コードの重複を避けます。
    8.5

    モジュール & インポート

    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.
    日本語

    モジュールは用意された関数のファイルです。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
    

    ** 一般的なミス **

    • 関数は None を返すが、return を記述しない限りである。印刷(printing)と返す(returning)は異なる。
    • def f(x=[]) のような可変型のデフォルト値は絶対に使わないでください — 全呼び出し間で同じリストが共有されます。
    • 関数内で作成された変数はローカルで、外からは見えません。
    • f() で関数を呼び出します。f だけを単に書くだけでは、それは名前に過ぎません。
  • 9 Errors, exceptions & testing · ⁨エラー、例外、テスト⁩
    9.1

    エラー & デバッグ

    English

    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.
    日本語

    コードは3つの方法で失敗します。構文エラーはPythonのルールを破るため、全く実行されません。ランタイムエラーは実行中に発生し、ゼロで割った場合などが該当します。ロジックエラーは実行されますが、正しくない答えを返します。

    # 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 は失敗した場所を示すトレースバックを印刷します。下から上へ読んでください。
    一般的なPythonのエラー: 構文, Name, Type, Index
    一般的なPythonのエラー: 構文, 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.
    日本語

    リスクのあるコードを try で囲みます。もし失敗すれば、except が例外をキャッチして処理し、クラッシュさせます。

    def to_int(text):
        try:
            return int(text)
        except ValueError:
            return 0
    
    print(to_int("42"))    # 42
    print(to_int("abc"))   # 0
    
    • 特定のタイプをキャッチします(ValueError, ZeroDivisionError, …)。
    • raise は意図的に独自のエラーを作ります。
    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

    テスト & ロバスト性

    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.
    日本語

    テストは、コードが正しい答えを返すか確認します。通常ケース および エッジケース(空の入力、ゼロ、非常に大きい値)を試してください。

    def average(nums):
        if len(nums) == 0:        # edge case: empty list
            return 0
        return sum(nums) / len(nums)
    
    print(average([2, 4, 6]))     # 4.0
    print(average([]))            # 0
    
    • ロバストなコードは奇妙な入力でもクラッシュせず、適切に処理します。

    ** 一般的なミス **

    • 裸の except: を使わないでください — 特定のエラーをキャッチし、例:except ValueError: 。
    • 構文エラーは実行される前にプログラム全体を停止させるため、それらを最初に修正してください。
    • 簡単なものだけでなく、エッジケース(空の入力、ゼロ、最大の値)もテストしてください。
  • 10 Files · ⁨ファイル⁩
    10.1

    テキストファイルの読み書き

    English

    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.
    日本語

    テキストファイルはディスク上にテキストを保存します。モードが read または write の open(name, mode) で開きます。with を常に使い、これがファイルを自動的に閉じてくれます。

    書き込み

    モード "w" は新しいファイルを作成し、古いものを消去します。

    with open("notes.txt", "w") as f:
        f.write("first line\n")
        f.write("second line\n")
    print("saved")            # saved
    

    読み込み

    モード "r" (デフォルト)は読み込みます。.read() はファイル全体を1つの文字列として返します。

    with open("notes.txt", "w") as f:
        f.write("hello\nworld\n")
    with open("notes.txt") as f:
        print(f.read().strip())   # hello / world
    

    ラインごとに

    ファイルに対してループしてラインごとに取得します。.strip() は末尾の改行を削除します。

    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
    

    追加

    モード "a" は追加 — 消去せずに末尾に追加します。

    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
    
    モード 意味
    "r" read (デフォルト)
    "w" write (先に消去)
    "a" append (末尾に追加)

    ** 一般的なミス **

    • ファイルを必ず閉じるか、with open(...) as f: を使うと自動的に閉じます。
    • read() はファイル全体を1つの文字列として返し、各ラインは依然として \n で終わります。
    • "w" で開くと先にファイルを消去します;末尾に追加するには "a" を使ってください。
    open → read/write → close (自動閉じ)
    open → read/write → close (自動閉じ)
  • 11 Algorithm design · ⁨アルゴリズム設計⁩
    11.1

    アルゴリズム & 分解

    English

    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.
    日本語

    アルゴリズムは問題を解決する明確な手順のリストです。分解とは、大きな問題を一度に解ける小さな部分に分割することです。

    # 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
    
    • 抽象とは詳細を無視することです:largest(...) を使う際、再びその仕組みを読む必要はありません。
    11.2

    疑似コード & フローチャート

    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.

    日本語

    擬似コードは、実際のコードより先に書かれる、アルゴリズムのための平明で構造化された英語です。実行することはできません。

    SET best TO first number
    FOR Each number n
        IF n > best
          THEN
            SET best TO n
            OUTPUT best
    

    フローチャートは同じ計画を描きます:各ステップにボックス、各判断にダイヤモンド、順序に矢印を使います。

    11.3

    再帰 & キャルスタック

    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.
    日本語

    再帰とは、関数が自分自身を呼び出すことです。ベースケース(すぐに返される単純な入力)と再帰ケース(より小さい入力で自分自身を呼び出す)が必要です。

    factorial(3)のコールスタック:各呼び出しは待機し、逆順で戻ります
    factorial(3)のコールスタック:各呼び出しは待機し、逆順で戻ります
    def fact(n):
        return 1 if n <= 1 else n * fact(n - 1)
    
    print(fact(5))     # 120
    
    • 各一時的な停止状態の呼び出しは、上の呼び出しが返るまでキャルスタックに残ります。

    ** 一般的なミス **

    • 再帰にはベースケースが必要で、そうでなければ永遠に自分自身を呼び出してキャルスタックをクラッシュさせます。
    • 擬似コードはプランニング用です — 実行する必要はありませんが、すべてのステップは曖昧でない必要があります。
    • どのコードを書く前に、大きな問題を名付けられた小さなステップに分割してください。
  • 12 Data structures · ⁨データ構造⁩
    12.1

    抽象データ型 (ADT)

    English

    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.

    日本語

    抽象データ型(ADT)は、データの組み込み方とは別々に、データとその操作を記述します。内部ストレージではなく、操作を通じて使います。

    # 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

    スタック

    English

    A stack 栈 is last-in, first-out (LIFO 后进先出). You push 压入 onto the top and pop 弹出 from the top.

    日本語

    スタックは後入れ先出し(LIFO)です。トップにpushし、トップからpopします。

    スタックはトップから取り除く(LIFO);キューは先頭から取り除く(FIFO)
    スタックはトップから取り除く(LIFO);キューは先頭から取り除く(FIFO)
    stack = []
    stack.append("a")
    stack.append("b")
    print(stack.pop())   # b
    print(stack.pop())   # a
    
    12.3

    キュー

    English

    A queue 队列 is first-in, first-out (FIFO 先进先出). You enqueue 入队 at the back and dequeue 出队 from the front.

    日本語

    キューは先入れ先出し(FIFO)です。後ろにenqueueし、先頭からdequeueします。

    queue = []
    queue.append("a")     # enqueue
    queue.append("b")
    print(queue.pop(0))   # a  (dequeue the front)
    print(queue.pop(0))   # b
    
    12.4

    リンクリスト

    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.

    日本語

    リンクドリストはノードの連鎖です。各ノードはデータと次のノードへのポインタを持ち、最後は None を指します。

    リンクドリスト:各ノードはデータと次のノードへのポインタを持ち、Noneで終わる
    リンクドリスト:各ノードはデータと次のノードへのポインタを持ち、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

    ハッシュテーブル

    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.

    日本語

    ハッシュテーブルはハッシュ関数を使ってキーをスロットにマッピングします。2つのキーが同じスロットに入ることがあります — これは衝突です。Pythonの dict はハッシュテーブルなので、検索が速いです。

    ハッシュ関数は各キーをスロットにマッピングし、2つのキーが1つのスロットで衝突することがある
    ハッシュ関数は各キーをスロットに割り当てます。2つのキーが同一个のスロットに衝突することがあります
    table = {}
    table["Mei"] = 88
    table["Sam"] = 71
    print(table["Mei"])   # 88  (fast lookup by key)
    
    12.6

    二分探索木

    English

    A binary search tree 二叉搜索树 (BST) keeps order: every left child is smaller than its node, every right child is larger. Search stays fast.

    日本語

    二項探索木(BST)は順序を維持します:すべての左の子ノードは親より小さく、すべての右の子ノードは親より大きいです。検索は高速です。

    二項探索木:小さい値は左へ、大きい値は右へ
    二項探索木:小さい値は左へ、大きい値は右へ
    def insert(root, val):
        if root is None:
            return {"val": val, "left": None, "right": None}
        if val < root["val"]:
            root["left"] = insert(root["left"], val)
        else:
            root["right"] = insert(root["right"], val)
        return root
    
    def inorder(root):
        if root is None:
            return []
        return inorder(root["left"]) + [root["val"]] + inorder(root["right"])
    
    tree = None
    for v in [5, 3, 8, 1, 4]:
        tree = insert(tree, v)
    print(inorder(tree))   # [1, 3, 4, 5, 8]
    
    12.7

    グラフ

    English

    A graph 图 is a set of vertices 顶点 joined by edges 边. An adjacency list 邻接表 — a dict of neighbour lists — is a common way to store one.

    Common mistakes

    • A stack is last-in-first-out; a queue is first-in-first-out. Do not mix them up.
    • Check whether a structure is empty before you pop or dequeue from it.
    • In a linked list, losing the head pointer loses the whole list.
    日本語

    グラフは、辺で結ばれた頂点の集合です。隣接リスト(近傍リストの辞書)は、それを格納する一般的な方法です。

    頂点と辺のグラフ、およびその隣接リスト形式
    頂点と辺のグラフ、およびその隣接リスト形式
    graph = {"A": ["B", "D"], "B": ["A", "C"], "C": ["B", "D"], "D": ["A", "C"]}
    for vertex in graph:
        print(vertex, "->", graph[vertex])
    # A -> ['B', 'D']  (and so on for B, C, D)
    

    ** 一般的なミス **

    • スタックは後入先出(LIFO)、キューは先入先出(FIFO)です。混同しないでください。
    • ポップまたはデキューする前に、構造体が空かどうか確認してください。
    • リンクedListにおいて、headポインタを失うと、リスト全体を失います。
  • 13 Searching, sorting & efficiency · ⁨検索、ソート、効率性⁩
    13.1

    線形探索と二分探索

    English

    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.

    日本語

    探索は値がある場所を探します。線形探索は順に各アイテムを確認するため、どんなリストでも機能します。

    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
    

    二項探索は遥かに速いですが、ソート済みリストが必要です。各ステップで範囲を半分にします。

    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
    
    二項探索は各ステップで範囲を半分にする — ソート済みリスト上でO(log n)
    二項探索は各ステップで範囲を半分にする — ソート済みリスト上でO(log n)
    13.2

    ソーティング(バブルソート & 挿入ソート)

    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():
    日本語

    ソートとはアイテムを並べ替えることです。バブルソートは、順番の異なる隣り合う要素を繰り返し交換します。

    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]
    

    挿入ソートは、アイテムを1つずつソート済みの部分に積み上げ、新しいアイテムを正しい位置までスライドさせていきます:

    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]
    
    • 実際のコードでは、Pythonの組み込み sorted() を使用します:
    print(sorted([5, 2, 4, 1]))           # [1, 2, 4, 5]
    
    13.3

    アルゴリズム効率

    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
    日本語

    効率は、入力が増加した際に作業量がいかに増えるかを問うものです。Big-OOを用いて記述します。

    How the number of steps grows with input size for common complexities
    一般的な計算複雑度における、入力サイズに対するステップ数の増加
    Big-O 名称 例
    $O(1)$ 定数 辞書のキーを参照
    $O(\log n)$ 対数 二項探索
    $O(n)$ 線形 線形探索
    $O(n^2)$ 二次 バブルソート
    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

    乱数とシミュレーション

    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.
    日本語

    randomモジュールは乱数を生成します。結果を再現可能にするためにシードを使用します。シミュレーションは多くの乱数試行を実行して答えを推定します。

    import random
    random.seed(0)
    rolls = [random.randint(1, 6) for _ in range(1000)]
    print(rolls.count(6))   # about 1/6 of 1000
    

    ** 一般的なミス **

    • 二項探索はソート済みリストでのみ機能します。
    • Big-Oは時間がどのように成長するかを示し、正確な時間ではありません;O(n²)の手法は、微小な入力に対してのみO(n)より速い場合があります。
    • バブルソートはO(n²)です — 学習には適していますが、大きなリストでは遅いです。
  • 14 OOP & paradigms · ⁨OOPとパラダイム⁩
    14.1

    クラスとオブジェクト

    English

    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:

    日本語

    クラスは設計図です。オブジェクトはそれから作られた1つの事物(インスタンス)です。__init__ は各オブジェクトを初期化するコンストラクタであり、self はオブジェクト自体です。

    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 は属性(オブジェクト上のデータ)であり、speak はメソッド(アクション)です。

    __str__ を追加して、print(obj) の表示を制御します:

    class Dog:
        def __init__(self, name):
            self.name = name
        def __str__(self):
            return f"Dog named {self.name}"
    
    print(Dog("Rex"))    # Dog named Rex
    
    クラスは設計図であり、呼び出すことでオブジェクトを作成します
    クラスは設計図であり、呼び出すことでオブジェクトを作成します
    14.2

    継承、カプセル化、多様性

    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.

    日本語

    継承によりサブクラスはスーパークラスの機能を再利用できます。親を呼び出すにはsuper() を使用し、メソッドをオーバーライドして変更します。

    class Animal:
        def speak(self):
            return "some sound"
    
    class Cat(Animal):
        def speak(self):                # override
            return "meow"
    
    print(Cat().speak())   # meow
    

    カプセル化はデータをメソッドの奥に隠し、先頭のアンダーバーで非公開としてマークします。

    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
    

    多様性とは、1つの名前で多くの振る舞いがあることを意味し、各オブジェクトに対して適切なspeak が実行されます。

    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

    プログラミングパラダイム

    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.
    日本語

    パラダイムはプログラムを書くスタイルです。手続的コードは一連の手順と関数の列です。オブジェクト指向コードはデータとメソッドをオブジェクトにまとめます。宣言的コードは「どうやるか」ではなく「何をするか」を指定します(リスト内包表記や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)
    

    ** 一般的なミス **

    • すべてのメソッドは最初の引数としてself を必要とします。
    • __init__ は新しいオブジェクトを初期化し、作成時に自動的に実行されます。
    • 同じクラスの2つのオブジェクトは別々の属性を持ち、片方を変更しても他方は変わりません。
  • 15 Data representation · ⁨データの表現⁩
    15.1

    Bits & binary

    English

    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:

    日本語

    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.

    Binary place values: 1101 means 8 + 4 + 1 = 13
    Binary place values: 1101 means 8 + 4 + 1 = 13
    print(bin(13))         # 0b1101
    print(int("1101", 2))  # 13
    
    • 8 bits make a byte 字节. A fixed width can overflow 溢出 (wrap around) when the number is too big.
    x = 250
    x = (x + 10) % 256     # one byte wraps at 256
    print(x)               # 4
    

    Hexadecimal 十六进制 (base 16) is a compact way to read binary: one hex digit stands for exactly four bits. Python writes hex with 0x:

    print(hex(255))        # 0xff
    print(0xFF)            # 255
    print(int("ff", 16))   # 255
    
    15.2

    Compression

    English

    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.
    日本語

    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.

    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
    

    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.
  • 16 Computing concepts · ⁨コンピュータ科学の概念⁩
    16.1

    コンピューティングとは & デザインサイクル

    English

    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.
    日本語

    コンピューティングとは、コンピュータを用いて問題を解決することです:入力、処理、出力。良質なソフトウェアは、計画・作成・テスト・改善を繰り返すデザインサイクルによって構築されます。

    • 問題を分解して小さな部分を作り、テストし、さらに追加します。
    • プログラマーはチームで働き、互いのコードを再利用します。
    16.2

    インターネット

    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
    日本語

    インターネットはネットワークのネットワークです。データはパケットに分割され、個別に送信されて相手が側で統合されます。TCP/IPのようなプロトコルと呼ばれる共有ルールがこの動作を可能にしています。あるパスが切断された場合、パケットは別の経路を取ります — これは冗長性であり、耐故障性を提供します。

    インターネットの地図:各線は2つのネットワーク間の経路です
    インターネットの地図:各線は2つのネットワーク間の経路です
    レイヤー 役割
    HTTP ウェブページの要求と送信
    TCP 信頼性のある配送、順序通り
    IP アドレッシングとルーティング
    16.3

    パラレルおよび分散コンピューティング

    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.
    日本語

    順次処理のコードは一度に1ステップしか実行しません。パラレルコンピューティングは多数のコアで複数のステップを同時に実行し、速度向上をもたらします。分散コンピューティングは、クラウドなど、多数のコンピュータに作業を分配します。

    • すべてが並列化できるわけではありません:一部のステップは、より前の結果を待たなければなりません。
    16.4

    コンピューティングの影響

    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.
    日本語

    コンピューティングには利点も害もあります。デジタル・ディバイドとは、すべての人が平等にアクセスできるわけではないことを意味します。ソフトウェアは、学習データから偏見を含んでしまうことがあります。知的財産権(ライセンス)を尊重し、個人の個人情報やプライバシーを保護してください。

    ** 一般的なミス **

    • インターネットとワールドワイドウェブは別物です:Webはインターネット上で動作する一つのサービスに過ぎません。
    • プロセッサのコア数が増えるのは、作業を同時に実行可能な部分に分割できる場合に限られます。
  • 17 Putting it together · ⁨統合⁩
    17.1

    エンドツーエンドミニプロジェクト

    English

    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.
    日本語

    ミニプロジェクトは、リスト内のデータ、ループ内の選択文を含む関数、そして印刷出力といったそれまでのアイデアを統合したものです。これはAP Create Performance Taskの形式そのものです。

    プロジェクト:平均点

    def average(marks):
        if len(marks) == 0:
            return 0
        return round(sum(marks) / len(marks), 1)
    
    print(average([88, 71, 95, 60]))   # 78.5
    

    プロジェクト:合格者のカウント

    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
    

    プロジェクト:新しいリストへのフィルタリング

    def merit(marks):
        return [m for m in marks if m >= 80]
    
    print(merit([88, 71, 95, 60]))     # [88, 95]
    

    AP Createタスクでは、リスト、選択と反復を使用するパラメータ付きプロシージャ、および入出力が必要です。上記の各プロジェクトはこの構造に完全に対応しています——小さな部品を組み立て、最後に結合してください。

    ** 一般的なミス **

    • 小さいステップで組み立て、次のステップに進む前に各部分をテストしてください——一度に全てを書き込まないでください。
    • コーディングの前にまずタスク全体を読み、入力 → 処理 → 出力の計画を立ててください。
    Mini-project: データ → 関数 → 印刷結果
    ミニプロジェクト:データ → 関数 → 印刷結果

Log in or create account · ⁨ログインまたはアカウント作成⁩

IGCSE, A-Level & AP