Selection and conditionals
導入済み
6:37
プログラミング基礎
Every program in this course is complete and runnable: type it, run it, then change one line. The whole skill is a loop. First predict what the code will do…
英語のナレーション・英語と中国語の字幕を切り替え可能
このレッスンの内容
| English | 意味 |
|---|---|
| program/ˈprəʊɡræm/ | A set of instructions specifying operations for a computer to carry out. |
| condition/kənˈdɪʃn/ | 条件 |
| comparisons | |
| selection/sɪˈlekʃn/ | 選択 |
| boundary/ˈbaʊndəri/ | A line, surface or limit that separates regions or marks the extent of an area or set. |
| input/ˈɪnpʊt/ | A value, signal or resource supplied to a function, program, device or process. |
| syntax error/ˈsɪntæks ˈerə/ | A mistake that breaks the grammatical rules of a programming language. |
なぜ年金受給者は学生料金で支払ったのか?
- シネマは子供および65歳以上が£5、学生が£7、それ以外が£10である。70歳の学生に£7が請求された。
- プログラム内のすべてのルールは正しく、単に正しい順序でテストされていません。このレッスンは、プログラムがどのような経路を選択するか、そしてなぜ順序が設計の一部なのかについてです。
条件とは真偽の質問である
- 条件とは、その値が
boolとなる式です:age >= 65,answer == "y",n != 0。比較演算子には<,<=,>,>=(等しい),==,!=(等しくない) があります。 - 条件を
and(両方が真である必要がある)、or(少なくとも一方が真であればよい)、not(反転させる) で結合します。3 >= 3 and not (2 > 5)はTrueです。
student = input("Student? y/n ") == "y" # already a bool
print(type(student)) # <class 'bool'>
What does print(3 >= 3 and not (2 > 5)) show?
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
3 >= 3 is True; 2 > 5 is False, so not (2 > 5) is True. Both sides are true, so and gives True.
if と else: 2つの経路のいずれか
if condition:は条件がTrueの場合のみインデントされたブロックを実行します。else:ブロックはFalseの場合に実行されます。2つの中でちょうど1つが実行されます。- インデント こそ がブロックです。
ifの下にインデントされた行はそのブロックに属し、左端に戻った最初の行は发生了什么にも関わりなく実行されます。
if total >= 50:
fee = 0
else:
fee = 5
print("Delivery:", fee) # always runs
A line that is not indented, written straight after an if block, runs only when the condition is True.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Only indented lines belong to the if. The first line back at the left edge is outside the block, so it runs either way.
elif: 最初の真の分岐が勝利する
- 選択において
if … elif … elseは条件を上から下へテストし、Trueとなった最初のものだけを実行します。他のすべてはスキップされ、もしそれらが真であっても同様です。 elseは残りをすべて受け取るため、完全なチェーンは常にちょうど1つの経路を必要とする。


A shop uses if total >= 50: fee = 0, then elif total >= 20: fee = 3, then else: fee = 5. What is fee when total is exactly 20?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
20 >= 50 is False, so the chain moves on; 20 >= 20 is True, so fee = 3 runs and the else is skipped. A boundary value is exactly the case worth testing.
フォールスルーを信頼する
elifに到達するのは、その上のすべてのテストが失敗した時だけである。したがってelif score >= 70はand score < 80を必要とせず、その行に到達することはすでにスコアが 80 未満であることを証明している。- 追加テストの記述は長く、境界におけるミスをする場所が1つ増える。
if score >= 80:
band = "A"
elif score >= 70: # here score < 80 is already known
band = "B"
elif score >= 60:
band = "C"
else:
band = "F"
どの分岐が実行されますか?
Drag the score and watch the chain test each condition from the top. Only the first true branch runs; at 79 the test score >= 80 fails and score >= 70 wins.
In the band chain, why does elif score >= 70: not need and score < 80?
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
各々 elif inherits the failure of every test above it. A score of 80 or more has already been caught by the first branch.
狭いルールを先に配置する
- 2つのルールが両方真となり得る場合、最初に記述されたルールが決定する。必ず勝つ必要があるルール(通常は狭いもの)を、広いルールの上に置く。
- 各経路から1つの入力値をテストし、2つのルールに一致する入力も1つテストする。この重複ケースに順序バグが隠れている。
- 子供および65以上は£5、学生は£7、その他は£10。
- 年齢を先に見る:
if age < 12 or age >= 65:→elif student:→else:。70歳の学生は £5 を支払う。 - 学生を先に見る:同じ人は
if student:に到達して £7 を支払う。両方のプログラムは、20歳の学生(£7)と30歳の人(£10)に対するテストを通過する。差が現れるのは重複ケースのみである。
Put the lines in order so that a 70-year-old student pays £5 and a 20-year-old student pays £7.
難易度 3/5 · 200 コイン + 今日初回達成時の小ボーナス
The age rule must win the overlap case, so it is tested first. A 20-year-old student fails the age test and reaches elif student:.
条件を組み合わせる際は注意
- Pythonでは比較を連鎖できる:
0 <= mark <= 100は0 <= mark and mark <= 100を意味する。 andは答えが判明した時点で即座に停止する。n != 0 and total / n > 5がゼロ除算をしないのは、nが0のとき左辺は既にFalseだからである。
Let x = 15. Which conditions are truthy (would be treated as true in an if statement)? Select all that apply.
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
The chain holds, and $15$ is a multiple of 5. not x > 10 is False. The last one is the trap: it means (x == 10) or 20, and 20 counts as true, so it is true for every x.
見落としやすいポイント
- 条件における
=。if x = 5:は構文エラーであり、比較には==が必要である。 x == 1 or 2。 これは(x == 1) or 2を意味し、2は真としてカウントされるため、テストは常に真となる。x == 1 or x == 2またはx in (1, 2)を記述すること。ifをelifの意図で分けた場合。 3つの独立したif文が全て実行されうるが、elifチェーンは1つだけ実行される。- 境界線。
>か>=か? 正確な境界値(例えばスコアがちょうど70の場合など)をテストする。
A program has three separate statements: if score >= 60: print("C"), if score >= 70: print("B"), if score >= 80: print("A"). What does it print for a score of 85?
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Separate if statements are each tested, so all three run. An if … elif chain with the highest band first would print only A.
The cinema code passes tests for a 30-year-old, a 20-year-old student and an 8-year-old. Which extra test would reveal that the student rule was put first?
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Only a customer who matches two rules shows which rule wins. A 70-year-old student should pay £5; with the student rule first, they pay £7.
理解できましたか
- 条件とは
bool式であり、and、or、notとの比較によって構築する。 if … elif … elseは上からテストを行い、最初のtrue分支のみを実行する;elseは残りの条件を受け取る。- 各
elifはそれより上のテストが失敗したことを既知としている。順序は設計である:必ず勝つルールを先におき、重複と境界のケースをテストする。
このカードは新しいため、翻訳ができるまで英語で表示されます。
You've got it
- A condition 条件 is a
boolexpression; build it from comparisons withand,orandnot. if … elif … elsetests from the top and runs only the first true branch;elsetakes what is left.- Each
elifalready knows that the tests above it failed. Order is design: put the rule that must win first, and test the overlap and boundary cases.
| Customer | Age test first | Student test first |
|---|---|---|
| 30-year-old | £10 | £10 |
| 20-year-old student | £7 | £7 |
| 70-year-old student | £5: correct | £7: wrong |
何が問題でしたか?この内容はサイトの運営チームだけが確認します。