Selection — IF and CASE
Esta página precisa de um navegador recente (com suporte a SharedArrayBuffer). Por favor, atualize Chrome, Edge, Firefox ou Safari para a versão mais recente.
English
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.
English
age = 20
if age >= 18:
print("You may vote")
English
else: the other path
elseruns when theiftest is false.- Exactly one of the two blocks runs.
English
mark = 45
if mark >= 50:
print("Pass")
else:
print("Fail")
English
elif: many paths
- Use
elifto test more conditions in order. - Python checks each test top to bottom and stops at the first true one.
English
temp = 22
if temp >= 30:
print("hot")
elif temp >= 15:
print("mild")
else:
print("cold")
Explorar
if / elif / else — which runs?
Tests run top-down; the primeiro true one runs, the rest are skipped.
English
Comparison operators
==means equal to (the exam writes=).!=means not equal to (the exam writes<>).- Also use
<,>,<=,>=.
English
print(5 == 5) # True
print(5 != 3) # True
print(3 <= 2) # False
English
In the exam: IF and CASE
- Pseudocode uses
IF … THEN … ELSE … ENDIF, orCASEfor many fixed choices.
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
English
Common mistakes
- Compare with
==, not=. - Cover every case, including the
else. - Indent the block that belongs to each branch.
English
Now you try
- Read the input, then choose what to print with
if/elif/else. - Press Check answer to test your code.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Read a whole number, then print even if it divides by 2 with no remainder, otherwise print odd. For input 4, print even.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
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.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Two numbers a e b are set for you. Use an if to store the maior one in biggest.
Clique em Executar para ver a saída aqui.