Selection — IF and CASE · 選択 — IF文とCASE文
Making a decision
- Selection means choosing what to do, based on a test.
- An
ifruns its block only when the test is true. - The test gives a Boolean:
TrueorFalse.
判断を行う
- **選択(Selection)**とは、テストに基づいて何をすべきかを選ぶことです。
ifブロックはテストが真の時にのみ実行されます。- テストの結果はブール値です:
TrueまたはFalse。
age = 20
if age >= 18:
print("You may vote")
else: the other path
elseruns when theiftest is false.- Exactly one of the two blocks runs.
else:もう一方の道筋
elseはifのテストが偽のときに実行されます。- 2つのブロックのうち、ちょうど1つが実行されます。
mark = 45
if mark >= 50:
print("Pass")
else:
print("Fail")
elif: many paths
- Use
elifto test more conditions in order. - Python checks each test top to bottom and stops at the first true one.
elif:複数の道筋
elifを使って条件を順にテストします。- Pythonは各テストを上から下へ確認し、最初に真となるものを見つけたら停止します。
mark = 72
if mark >= 70:
print("A")
elif mark >= 50:
print("B")
else:
print("C")
if / elif / else — which runs? · if / elif / else — どれが実行されますか?
Tests run top-down; the first true one runs, the rest are skipped. · テストは上から下へ実行され、最初に真となるものが実行され、残りはスキップされます。
Comparison operators
==means equal to (the exam writes=).!=means not equal to (the exam writes<>).- Also use
<,>,<=,>=.
比較演算子
==は等しい(試験では=と書きます)。!=は等しくない(試験では<>と書きます)。- また、
<、>、<=、>=も使います。
print(5 == 5) # True
print(5 != 3) # True
print(3 <= 2) # False
In the exam: IF and CASE
- Pseudocode uses
IF … THEN … ELSE … ENDIF, orCASEfor many fixed choices.
試験向け:IFとCASE
- 擬似コードでは
IF … THEN … ELSE … ENDIFを使用し、多数の固定された選択肢がある場合はCASEを使います。
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Common mistakes
- Compare with
==, not=. - Cover every case, including the
else. - Indent the block that belongs to each branch.
よくあるミス
- ⟨
==⟩ で比較し、=で比較しないでください。 elseを含むすべてのケースを網羅します。- 各分支に対応するブロックをインデントします。
Now you try
- Read the input, then choose what to print with
if/elif/else. - Press Check answer to test your code.
あなたも試してみよう
- 入力を読み取った後、
if/elif/elseを使って出力应选择什么。 - 回答を確認 を押してコードを試してください。
Read a whole number, then print even if it divides by 2 with no remainder, otherwise print odd. For input 4, print even. · 整数を読み込み、2 で割り切れる余りがあれば even を出力し、そうでなければ odd を出力してください。入力 4 に対しては、even を出力します。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Read a mark (0–100). Print A for 70 or more, B for 50–69, and C for anything less. For input 65, print B. · 点数(0–100)を読み込み、70点以上ならA、50–69点ならB、それ以外ならCを出力してください。入力65に対しては、Bを出力してください。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Two numbers a and b are set for you. Use an if to store the larger one in biggest. · 2つの数 a と b が与えられています。 if を使用して、より大きい方を biggest に格納します。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。