9. if
else
statement¶
The if
else
statement is used to execute a block of code if a condition is met and a different block of code if the condition is not met.
This is a control flow statement, that is, it controls the order in which the instructions of the program are executed.
Example:
edad = input('Escribe tu edad: ')
edad = int(edad)
if edad >= 18:
print("Eres mayor de edad")
else:
print("Eres menor de edad")
In this example, if the variable "age" is greater than or equal to 18, "You are of legal age" will be printed. Otherwise, "You are a minor" will be printed.
code indentation¶
In Python, statements belonging to the if
block must be written with an offset to the right called an indentation.
This indentation, by convention, is 4 spaces. You can offset the code a different number of spaces and it will work, but it's a good idea to stick to this custom because it's what most Python programmers do.
All statements that are offset will be executed depending on whether the if
statement is true. Orders that are not moved will always be executed:
condicion = True
if condicion == True:
print('Este print() se ejecuta solo si la condición es verdadera')
print('Este print() también')
print('Este print() se ejecuta siempre, independientemente del if')
print('Porque este bloque ya no pertenece al if')
In other programming languages, you also have to move the code to the right to improve the visualization of the program structure, but it is not mandatory, since there are statements or characters that precisely define the start and end of each block.
In Python, on the other hand, it is mandatory to indent the code so that the program can work without problems.
If the offset of the lines of code is not regular, an error will also be thrown:
if True:
print('Hola')
print('mundo')
^
Error en este punto porque no coinciden las sangrías
de las dos instrucciones.
Later we will see how this displacement or indentation is used in all Python statements that end with a colon ':' and that have subordinate code blocks, such as loops, functions, classes, etc.
Exercises¶
Write a program that checks if a number is positive or negative and prints the result on the screen.
Clue:
num = input('Escribe un número: ') num = int(num) if num ... :
Write a program that checks if a number is even or odd.
To know if a number is even (divisible by two) it is necessary to calculate the remainder of the division by two. If the remainder is zero it means that the number is divisible by two and is even.
Clue:
if (num % 2 == 0): print('...') else: print('...')
Write a program that asks for two numbers and writes which of the two is greater than the other.
Escribe un programa que compruebe si una condición es verdadera o es falsa. Comprueba que el programa funciona tanto si la condición es verdadera (True) como si es falsa (False).
Clue:
condicion = True if condicion: print('...') else: print('...')
Write a program that asks for a grade and checks if the grade is passed or failed.
Write a program that asks for a password and checks if the password is equal to the word 'secret'. If so, you must write 'correct password' on the screen. Otherwise you must write 'wrong password' on the screen.