選択を作る
ifは条件が真の時にのみコードを実行します。- 条件の後にコロン
:が続きます。 ifに属する行はインデント(スペース4つ)されています。
比較
- 条件は通常、TrueまたはFalseとなる比較です。
==等しい、!=等しくない、<><=>=。- 注意:
==は等価性をテストします; 単一の=は値を格納します。
temperature = 30
if temperature > 25:
print("It is hot.")
if / elif / else
elif("else if")は最初の条件が偽の場合に別の条件をチェックします。elseはどの条件も真でなかった場合に実行されます。- Pythonは順序通りチェックし、最初に真になったところで停止します。
hour = 14
if hour < 12:
print("Morning")
elif hour < 18:
print("Afternoon")
else:
print("Evening")
余り
a % bはaをbで割った時の残りです。year % 4 == 0は、年が4でちょうど割り切れることを意味し、余りがないことを示します。8 % 3は2です。なぜなら、8は3が2個あり、2の余りがあるからです。
条件を組み合わせる
andは両方の側が真の時のみに真です。orは少なくとも一方の側が真の時に真です。notは真を偽に、偽を真に反転させます。
day = "Sat"
if day == "Sat" or day == "Sun":
print("Weekend!")
Cambridge擬似コードにおける表現
- Pythonの
if/elif/elseは、試験のIF … ELSE … ENDIFおよびCASEに対応しています。
IF Score >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
CASE OF Grade
"A": OUTPUT "Top"
"B": OUTPUT "Good"
OTHERWISE OUTPUT "Keep trying"
ENDCASE
よくあるミス
==と比較してください; 単一の=は代入です。elifを書き、else ifを書かず、各行のif/elif/elseの最後に:を付けます。if以下のインデントされたブロックは、条件が真の時に実行されます。
あなたも試してみよう
- 実行的时候,请在コード下のボックスに入力して Enter キーを押してください。
- チェックは入力を自動で入力します。読み取ってから、何を出力するかを判断してください。
- 出力テキストを正確に一致させてください。
if / elif / else
Conditions are checked top-down; only the first true branch runs.
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Read a score with int(input()). Print Pass if it is 50 or more, otherwise print Fail. For input 72, print Pass.
実行ボタンをクリックして出力を確認してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Read a score. Print A if it is 80+, B if it is 60+, otherwise C. Use if / elif / else. For input 75, print B.
実行ボタンをクリックして出力を確認してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Read an age. Print Yes if the age is from 13 から 19 (a teenager), otherwise No. Use and. For input 16, print Yes.
実行ボタンをクリックして出力を確認してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Read a year with int(input()). A year divides by 4 when the remainder is 0: year % 4 == 0. Print Leap if it divides by 4, otherwise Common. For the input 2024, print Leap.
実行ボタンをクリックして出力を確認してください。
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
Dividing by 4 is not the whole rule. A year that also divides by 100 is ~ではない a leap year, unless it divides by 400 too. 1900 is the trap: it divides by 4 and by 100, so print Common. Print Leap または Common.
実行ボタンをクリックして出力を確認してください。