Making decisions · Tomando decisões
Making a choice
ifruns some code only when a condition is true.- The condition is followed by a colon
:. - The lines that belong to the
ifare indented (4 spaces).
Fazendo uma escolha
ifexecuta algum código apenas se uma condição for verdadeira.- A condição é seguida por dois pontos
:. - As linhas que pertencem ao
ifestão recuadas (4 espaços).
Comparisons
- A condition is usually a comparison that is True or False.
==equal,!=not equal,<><=>=.- Note:
==tests equality; a single=stores a value.
Comparações
- Uma condição geralmente é uma comparação que resulta em True ou False.
==igual,!=diferente,<><=>=.- Nota:
==testa igualdade; um único=armazena um valor.
temperature = 30
if temperature > 25:
print("It is hot.")
if / elif / else
elif("else if") checks another condition if the first was false.elseruns when none of the conditions were true.- Python checks them in order and stops at the first true one.
if / elif / else
elif("else if") verifica outra condição se a primeira foi falsa.elseexecuta quando nenhuma das condições foi verdadeira.- Python as verifica na ordem e para na primeira verdadeira.
hour = 14
if hour < 12:
print("Morning")
elif hour < 18:
print("Afternoon")
else:
print("Evening")
The remainder
a % bis what is left over whenais divided byb.year % 4 == 0means the year divides by 4 exactly — nothing left over.8 % 3is2, because 8 is two 3s with 2 left over.
O resto
a % bé o que sobra quandoaé dividido porb.year % 4 == 0significa que o ano divide por 4 exatamente — nada sobra.8 % 3é2, pois 8 são dois 3s com 2 sobrando.
Combine conditions
andis true only when both sides are true.oris true when at least one side is true.notflips true to false and false to true.
Combinar condições
andé verdadeiro apenas quando ambos os lados são verdadeiros.oré verdadeiro quando pelo menos um lado é verdadeiro.notinverte true para false e false para true.
day = "Sat"
if day == "Sat" or day == "Sun":
print("Weekend!")
In Cambridge pseudocode
- Python
if/elif/elsematches the exam'sIF … ELSE … ENDIFandCASE.
Em pseudocódigo do Cambridge
- Python
if/elif/elsecorresponde aoIF … ELSE … ENDIFeCASEdo exame.
IF Score >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
CASE OF Grade
"A": OUTPUT "Top"
"B": OUTPUT "Good"
OTHERWISE OUTPUT "Keep trying"
ENDCASE
Common mistakes
- Compare with
==; a single=assigns. - Write
elif, notelse if, and end eachif/elif/elseline with:. - The indented block below
ifis what runs when the condition is true.
Erros comuns
- Compare com
==; um único=atribui. - Escreva
elif, nãoelse if, e termine cada linha deif/elif/elsecom:. - O bloco recuado abaixo de
ifé o que é executado quando a condição é verdadeira.
Now you try
- When you Run, type the input in the box under the code and press Enter.
- The checks type the input for you. Read it, then decide what to print.
- Match the output text exactly.
Agora você tenta
- Ao clicar em Executar, digite a entrada na caixa abaixo do código e pressione Enter.
- Os checks digitam a entrada para você. Leia-a, depois decida o que imprimir.
- Corresponda ao texto de saída exatamente.
if / elif / else
Conditions are checked top-down; only the first true branch runs. · Condições são verificadas de cima para baixo; apenas o primeiro ramo verdadeiro roda.
Read a score with int(input()). Print Pass if it is 50 or more, otherwise print Fail. For input 72, print Pass. · Leia uma nota com int(input()). Imprima Pass se for 50 ou mais, caso contrário imprima Fail. Para entrada 72, imprima Pass.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Leia uma nota. Imprima A se for 80+, B se for 60+, caso contrário C. Use if / elif / else. Para entrada 75, imprima B.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Read an age. Print Yes if the age is from 13 to · até 19 (a teenager), otherwise No. Use and. For input 16, print Yes. · Leia uma idade. Imprima Yes se a idade estiver de 13 a 19 (um adolescente), caso contrário No. Use and. Para entrada 16, imprima Yes.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Leia um ano com int(input()). Um ano é divisível por 4 quando o resto é 0: year % 4 == 0. Imprima Leap se for divisível por 4, caso contrário Common. Para a entrada 2024, imprima Leap.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Dividing by 4 is not the whole rule. A year that also divides by 100 is not · não 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 or · ou Common. · Dividir por 4 não é a regra completa. Um ano que também divide por 100 não é bissexto, a menos que divida por 400 também. 1900 é a armadilha: ele divide por 4 e por 100, então imprima Common. Imprima Leap ou Common.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.