Language: EN

python-condicionales

Conditionals in Python

Conditionals are control structures that allow a program to make decisions based on certain conditions.

These statements allow us to evaluate expressions and execute different blocks of code depending on whether these expressions are true or false.

In Python, conditionals are mainly implemented through the if, elif (short for “else if”), and else statements.

If you want to learn more
consult the Introduction to Programming Course read more

if Statement

The if statement is used to execute a block of code if a condition is true. The basic syntax is as follows:

if condition:
    # block of code if the condition is true

For example, we can use an if to check if a number is greater than 10:

number = 15

if number > 10:
    print("The number is greater than 10")

In this case, since the number > 10 condition is true, the print will be executed and we will see “The number is greater than 10” in the output.

else Statement

The else statement is used to execute a block of code when the condition in the if is false. The syntax is as follows:

if condition:
    # block of code if the condition is true
else:
    # block of code if the condition is false

Following the previous example, we could add an else to handle the case where the number is not greater than 10:

number = 5

if number > 10:
    print("The number is greater than 10")
else:
    print("The number is less than or equal to 10")

In this case, since number is 5 and the number > 10 condition is false, the block of code inside the else will be executed and we will see “The number is less than or equal to 10” in the output.

elif Statement

The elif statement is used to evaluate multiple conditions sequentially. It is a shortening of “else if”.

The syntax is as follows:

if condition_1:
    # block of code if condition_1 is true
elif condition_2:
    # block of code if condition_1 is false and condition_2 is true
else:
    # block of code if all previous conditions are false

Let’s see an example where we use elif to classify a number in relation to 0:

number = 5

if number > 0:
    print("The number is positive")
elif number < 0:
    print("The number is negative")
else:
    print("The number is zero")

In this case, since number is 5 and is greater than 0, the first block of code will be executed and we will see “The number is positive” in the output.

Multiple Conditions

It is also possible to combine multiple conditions using the and, or, and not operators. These operators allow us to build more complex conditions:

  • and: Returns True if both conditions are true.
  • or: Returns True if at least one of the conditions is true.
  • not: Returns True if the condition is false.

For example:

x = 10
y = 5
z = 0

if x > y and y > z:
    print("All conditions are true")

In this case, all three conditions are true (x > y, y > z, and x > z), therefore, the print will be executed.