ifで判断する
Pythonは、ifと各elifを上から調べ、条件がTrueである最初の分岐だけを実行します。残りは飛ばされます。
年齢で変わる入場料
新しい構文の前に、試してみる問題です。小さな科学博物館(この例のための架空のもの)は、7歳未満の子どもは無料、7歳から18歳は3,000ウォン、それ以外の人は5,000ウォンです。年齢が与えられたら、プログラムが料金を出力するようにします。まず、規則を普通の言葉で、受付で尋ねる順に、問いのリストとして書いてみましょう。
おそらくこんなふうに書いたでしょう。来館者は7歳より小さいか。そうなら無料で、終わり。そうでなければ、18歳以下か。そうなら3,000ウォンで、終わり。それ以外は5,000ウォン。これでもうプログラムです。Pythonは「もし」「そうでなければもし」「それ以外」を、if、elif、elseと綴ります。
age = 12
if age < 7:
price = 0
elif age <= 18:
price = 3000
else:
price = 5000
print(price)3000構文の3つの細部が大切です。各条件の行はコロンで終わります。枝に属する行はインデントされ、Pythonチュートリアルは空白4つを勧めています。インデントが終わると、枝も終わります。そのためprint(price)は年齢に関係なく実行されます。そして実行される枝は1つだけです。年齢12なら、最初の条件はFalse、2番目はTrueなので、priceは3000になり、elseは見られません。
比較はTrueかFalseを返す
| 演算子 | 意味 | 例 | 結果 |
|---|---|---|---|
| == | 等しい | 5 == 5 | True |
| != | 等しくない | 5 != 5 | False |
| < | より小さい | 3 < 7 | True |
| <= | 以下 | 7 <= 7 | True |
| > | より大きい | 3 > 7 | False |
| >= | 以上 | 18 >= 19 | False |
等号が2つであることに注意してください。=1つは値を代入し、2つの==は比較します。文字列も比較できます。"kimchi" == "Kimchi"はFalseです。大文字は別の文字として数えられるからです。
elifの行の順序が答えを変える
Pythonは最初のTrueの条件で止まるので、枝の順序が大切です。点数の採点が典型的な例です。まず90以上を調べ、次に80、次に70を調べます。70の確認を先に置くと、95がそれに捕まってCになります。95 >= 70もTrueだからです。
score = 95
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(grade)Aand、or、notは条件をつなぐ
andは両側がTrueのときだけTrueです。orは少なくとも片側がTrueならTrueです。notはTrueとFalseを反転します。「13から18の間」のような条件は、age >= 13 and age <= 18と書くか、Pythonの短い形13 <= age <= 18で書けます。条件は別の枝の中に置くこともでき、これを入れ子と呼びます。韓国の中学校の情報科のカリキュラムは、プログラミングの基準の1つで、論理演算と入れ子の制御構造の両方を挙げています。
age = 15
has_ticket = True
if 13 <= age <= 18 and has_ticket:
print("Teen entry")
if not has_ticket or age < 7:
print("See the desk")
else:
print("Go in")Teen entry
Go in| if | 条件がTrueのときだけ、インデントされた行を実行する |
| elif | 「そうでなければ、もし」:上のすべてがFalseだったときだけ調べる |
| else | 上の条件がどれもTrueでなかったときに実行する |
| == | 2つの値を比べる。=は代入する |
| and / or / not | 両方が真/少なくとも一方が真/反対 |
| インデント | どの行が枝に属するかを示す、空白4つ |
- このコードは何を出力しますか。
x = 8 if x > 5: print("big") else: print("small") - このコードは何を出力しますか。
age = 7 if age < 7: print("free") elif age <= 18: print("3000") else: print("5000") - このコードは何を出力しますか。
score = 85 if score >= 70: print("C") elif score >= 80: print("B") - このコードは何を出力しますか。
x = 3 if x > 5: print("A") print("B")A
BBA(nothing)
- このコードは何を出力しますか。
print(5 == 5.0, "a" == "A") - このコードは何を出力しますか。
t = 30 print(t > 25 and t < 28) - このコードは何を出力しますか。
rain = False print(not rain) - このコードは何を出力しますか。
n = 14 if n % 2 == 0: if n > 10: print("big even") else: print("small even") else: print("odd") - xが10かどうかを正しく調べる行はどれですか。
- if x = 10:
- if x == 10:
- if x == 10
- if (x = 10)
- プログラムが"Even"を出力するように、行を並べてください。出力
Even
- 「if score = 90:は、scoreが90かを調べる。」 =1つは代入です。PythonはSyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?で止まります。if score == 90:と書きましょう。
- 「if answer == "yes" or "y":は、両方の答えを受け付ける。」 Pythonはこれを(answer == "yes") or ("y")と読み、"y"のような空でない文字列は真とみなされるので、条件は常に真です。answer == "yes" or answer == "y"と書きましょう。
- 「インデントは見た目だけ。」 Pythonでは、どの行が枝に属するかを決めます。忘れると、プログラムはIndentationError: expected an indented block after 'if' statement on line 2で止まります。
- if / elif / else:最初のTrueの枝だけが実行される。
- 条件の行は:で終わり、枝は空白4つでインデントする。
- ==は比較し、=は代入する。
- elifの連なりでは、最も厳しい条件を最初に置く。
- and、or、notは条件を組み合わせる。
このコースの出典 (6)
- Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
- Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
- Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
- General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
- Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
- Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)
確認日: 2026-10-19