Making decisions · Tomar decisiones
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).
Tomar una decisión
ifejecuta código solo cuando una condición es verdadera.- La condición va seguida de dos puntos
:. - Las líneas que pertenecen al
ifestán indentadas (4 espacios).
Comparisons
- A condition is usually a comparison that is True or False.
==equal,!=not equal,<><=>=.- Note:
==tests equality; a single=stores a value.
Comparaciones
- Una condición suele ser una comparación que es Verdadera o Falsa.
==igual,!=no igual,<><=>=.- Nota:
==prueba igualdad; un solo=almacena un 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("si no") verifica otra condición si la primera fue falsa.elsese ejecuta cuando ninguna de las condiciones fue verdadera.- Python las revisa en orden y se detiene en la primera verdadera.
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.
El resto
a % bes lo que sobra cuandoase divide porb.year % 4 == 0significa que el año se divide exactamente entre 4 — no sobra nada.8 % 3es2, porque 8 contiene dos 3s con 2 de sobrante.
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 condiciones
andes verdadero solo cuando ambos lados son verdaderos.ores verdadero cuando al menos uno de los lados es verdadero.notinvierte verdadero a falso y falso a verdadero.
day = "Sat"
if day == "Sat" or day == "Sun":
print("Weekend!")
In Cambridge pseudocode
- Python
if/elif/elsematches the exam'sIF … ELSE … ENDIFandCASE.
En pseudocódigo de Cambridge
- Python
if/elif/elsecoincide con elIF … ELSE … ENDIFyCASEdel examen.
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.
Errores comunes
- Compare usando
==; un solo=asigna. - Escriba
elif, noelse if, y termine cada líneaif/elif/elsecon:. - El bloque indentado debajo de
ifes lo que se ejecuta cuando la condición es verdadera.
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.
Ahora tú intentas
- Cuando Ejecutes, escribe la entrada en el cuadro debajo del código y presiona Enter.
- Los chequeos escriben la entrada por ti. Léele, luego decide qué imprimir.
- Coincide con el texto de salida exactamente.
if / elif / else
Conditions are checked top-down; only the first true branch runs. · Las condiciones se verifican de arriba hacia abajo; solo se ejecuta la primera rama que sea verdadera.
Read a score with int(input()). Print Pass if it is 50 or more, otherwise print Fail. For input 72, print Pass. · Leer una puntuación con int(input()). Imprimir Pass si es 50 o más, de lo contrario imprimir Fail. Para la entrada 72, imprimir Pass.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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. · Leer una puntuación. Imprimir A si es 80 o más, B si es 60 o más, de lo contrario C. Usar if / elif / else. Para la entrada 75, imprimir B.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Read an age. Print Yes if the age is from 13 to · hasta 19 (a teenager), otherwise No. Use and. For input 16, print Yes. · Leer una edad. Imprimir Yes si la edad está entre 13 y 19 (un adolescente), de lo contrario No. Usar and. Para la entrada 16, imprimir Yes.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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. · Leer un año con int(input()). Un año se divide por 4 cuando el resto es 0: year % 4 == 0. Imprimir Leap si se divide por 4, de lo contrario Common. Para la entrada 2024, imprimir Leap.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Dividing by 4 is not the whole rule. A year that also divides by 100 is not · no 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 Common. · Dividir por 4 no es toda la regla. Un año que también se divide por 100 no es bisiesto, a menos que también se divida por 400. 1900 es la trampa: se divide por 4 y por 100, así que imprimir Common. Imprimir Leap o Common.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.