age = 21 # int
price = 4.20 # float
name = "Ada" # str
open_ = True # bool
print(type(age)) # <class 'int'>
変数は値に紐付けられた名前であり、代入 age = 22 は名前の紐付けを再定義する —
古い値自体は編集されない。学位課程全体を通じて意識しておくと良い心的イメージ:
名前は箱につけられたタグであり、式は箱を読み出して新しい箱を作る
式を読むとは「箱を開けて計算し、新しい箱を閉じる」ことである:count * 3.50count = 6 を用いると int ボックス 6 と float ボックス 3.50 が開き、Pythonの混合
rule promotes the int — the result is the float21.0, never the int 21.
実行すると Python は TypeError: can only concatenate str (not "int") to str を raised します —
規則は推測を拒否します。修復は変換を明示的に名指しします:
print("Sold " + str(count) + " today")、またはよりクリーンな print("Sold", count, "today"), which inserts the spaces for you. The lesson to carry: + は数値に対して加算、文字列に対して結合であり、決して
暗黙の混合ではありません。
Branches are tested top to bottom; the first true branch wins and the rest are
スキップされます。
Indentation is not decoration — it IS the block. One extra space changes which
線が分岐に属するかどうかが変わります。
temp = 37.5
if temp >= 38:
print("Fever")
elif temp >= 36 and temp < 38:
print("Normal")
else:
print("Low")
実例1(映画館の料金)。 12または65+の場合、料金は5、学生は7、
それ以外の人は10:
age = int(input("Age? "))
student = input("Student? y/n ") == "y"
if age < 12 or age >= 65:
price = 5
elif student:
price = 7
else:
price = 10
print("Pay", price)
顺序很重要:第一个为真的分支胜出,这就是为什么年龄检查先于学生检查,
student check — a 70-year-old student should pay 5, and this ordering says so. Run
it with 70 and y to see the flowchart's leftmost path taken.
各 2 は一つの比較のみで十分である、なぜならそれ以上のテストですでに
where each elif only needs one comparison, because the tests above it have already
failed:
score = int(input("Score? "))
if score >= 80:
band = "A"
elif score >= 70:
band = "B"
elif score >= 60:
band = "C"
else:
band = "F"
print("Band:", band)
Common mistakes. Writing = where == is meant — the classic bug, and Python
refuses it in conditions (SyntaxError) precisely because it is so common. Testing
the special case after the general one, so the general one always wins. Using
elif に、より前の分岐で既に処理されたため到達不可能な条件を指定します。
捕まえた場合です。
5,000 の請求書を手作業で処理することはキャリアであり、ループを使えばプログラムになる。反復
は作業を繰り返す: for ループは既知のシーケンスを順にたどる; while ループは条件が成立している間実行される。設計上の問いは常に、移動回数が分かっているか、それとも条件で決まるかである。
条件が成立します。設計上の重要な点は、反復回数が既知か、それとも条件によって決まるかです。
どちらか?
total = 0
for i in range(1, 101): # 1..100 — range stops BEFORE its end
total += i
print(total) # 5050
反復回数が既知の場合は for を使い、条件で決まる場合は while を使います。すべての
while にはコード上で確認できる3つの要素が必要です:変数の初期値、条件式、そして終了に向かう変化 —否则は無限ループになります。
and something inside that moves toward exiting — otherwise it is an infinite
ループ。
階乗ループのトレース表
n = 5
factorial = 1
while n > 1:
factorial *= n
n -= 1 # the step toward exiting
print(factorial) # 120
balance = 1000.0
years = 0
while balance < 2000.0: # the condition itself is the goal
balance *= 1.05
years += 1
print(years, round(balance, 2)) # 15 2078.93
同じ価格計算が5箇所に現れます;税率ルールが変わり;そのうち4つが
を定義し、呼び出しが実行されます。
once and trusted everywhere: parameters in, a return value out. def
defines; calling runs.
def total_price(count, unit=3.50):
"""Return the total for count items at unit price."""
return count * unit
print(total_price(6)) # 21.0
print(total_price(6, unit=4.0)) # 24.0
引数(count)を提供します。デフォルト値(unit)により、引数は任意となります。
argument (6). A default value (unit=3.50) makes an argument optional.
return hands a value back and ends the call; printing is not returning — a
function without return returns None, and the caller that tries arithmetic on it
gets a TypeError.
def is_prime(n):
if n < 2:
return False
d = 2
while d * d <= n: # only test up to the square root
if n % d == 0:
return False # found a divisor — answer known, stop
d += 1
return True
print([p for p in range(2, 30) if is_prime(p)])
# [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
ここで2つの関数の習慣が出会います:早期の return は答えが出た瞬間に呼び出しを終了します。
既知である(フラグ変数は不要)。ループの上限 d * d <= n は、
$a \le b$で$n = a \times b$ならば$a \le \sqrt{n}$であるため、$\sqrt{n}$を超える範囲でのテストは既に確認済みの約数を再テストすることになる。
実行すると:リストはちょうど30未満の素数となる。
よくある間違い。 結果をリターンする代わりに関数内で印刷してしまうため、結果を再利用できない。
cannot be reused. Forgetting the return on one branch — that path quietly yields
None. Reaching into a function's locals from outside; they are gone when the call
呼び出しが終了するとそれらは消滅する。
A café's till needs the day's orders in order, the menu by name, a location that
must not drift, and today's unique drinks. Four jobs, four containers — choosing
それらの中から選ぶことが、モジュール1.5における設計判断である。
A list is an ordered, changeable sequence: marks = [72, 85, 61], indexed
from 0, sliced with marks[1:3]. A dictionary maps keys to values:
price = {"flat white": 3.5, "tea": 2.8}、keyによって読み書きされます。タプル
は固定された配列 (53.1, -1.5)であり、変更してはならない座標などに適しています。セット
は順序を持たない一意の要素を保持します: {"a", "b"}。
marks = [72, 85, 61]
marks.append(90) # [72, 85, 61, 90]
best = max(marks) # 90
average = sum(marks) / len(marks) # 77.0
エイリアス: 2つの名前で1つのリスト
代入ではコピーが行われません: a = [1]; b = a; b.append(2)が a を [1, 2] にします — リストは共有され、名前は別物です。この エイリアス は、
共有されているのはデータですが、名前ではありません。この别名化は、ユニット 1.1 のボックスが再び二重ラベル付きになったことで説明されます。
with two tags on one box, and it explains the next rule too: mutating a list while
looping over it skips elements — loop over a copy (for m in marks[:]) or build a
new list.
The dictionary's .get(key, 0) supplies 0 for a first sighting — the idiom that
** worked example orders (その日のベストセラー、拡張版) 。** カウントに基づき、
上位アイテムとそのカウントを報告します:
演習例 2(当日のベストセラー、段階的処理)。 集計に基づき、
最上位の項目とその件数を報告する:
best = max(tally, key=tally.get)
print(best, tally[best]) # tea 3
key=tally.get引数はmaxに対して、アルファベット順ではなく件数に基づいて項目を比較させる
——同じkey=の手法は、任意のカスタム指標で集合を並べ替えることも可能である。
escalation matters: real programs chain these tools (count, then rank) rather than
re-scanning orders twice.
カフェが閉まり、停電が発生しても、朝の集計結果が残っているのは、
プログラムがそれをディスクに書き込んでいた場合のみである。ファイルはプログラムの実行期間を超える。with open(path) as f: opens, closes on exit, and reads text; open(path, "w") で書き込みます
(かつ最初に空にする——これが古典的なミスである)。
with open("log.txt", "w") as f:
f.write("opened\n")
with open("log.txt") as f:
for line in f:
print(line.rstrip()) # rstrip removes the trailing newline
** worked example 1(欠落した設定ファイル).** 設定ファイルからテキストサイズを読み込む
存在しない場合や、整数値を保持していない可能性があるファイル:
try:
with open("settings.txt") as f:
size = int(f.read().strip())
except FileNotFoundError:
size = 12 # no file yet: a sensible default
except ValueError:
size = 12 # the file holds "big", not a number
print("Text size", size)
中央のテストを手動で確認します:小計 1003、10%引きで 902.7、そして
int(...) rounds down to 902. Notice the first assert too: at 200 pence and four
cup で合計は803 のまま — 境界テストは割引が発生することと、過早に発生しないことを証明する。
リストではなく連鎖として学ぶ:電荷が移動し、その速度が電流であり、電位差を通じたエネルギー移動の速度が電力である。