Language: EN

programacion-condicionales

What are conditionals

Conditionals are flow control structures that allow a program to make decisions based on the evaluation of one or more conditions.

Conditionals allow us to create branches in the program flow, executing certain instructions only if a certain condition is met.

Conditionals are essential for programming. In fact, they are the foundation of programming. Without conditionals, programs would be a flow of instructions that are executed from the beginning to the end. We could only make “calculators”.

Precisely the “grace” of programming is that, in addition to arithmetic behavior (doing calculations), we can give logic to our programs. This logic is achieved thanks to conditionals.

Thanks to conditionals, a program can be like one of those games or books where we have to make decisions. Depending on the decision we make, we can have one ending or another.

So, thanks to conditionals, our program can have many possible execution paths and many possible “endings”.

We can represent a conditional using the following symbol, which is more or less standard in flowcharts.

programacion-condicional-simbolo

Understanding conditionals

Conditionals are easy-to-understand structures. In fact, we constantly use them in our everyday lives. For example when we say.

If it rains, then I’ll take an umbrella

In this case, we have a simple conditional. If the condition is met (raining), we take the umbrella. If not, we do nothing. We could represent it like this

programacion-condicional-sencillo

This type of conditional is usually called IF, and in code it would look something like this,

if it rains:
    // take umbrella

Another example of a conditional could be needing an alternative action. This action will only be executed if the condition is not true. For example,

If it rains, then I’ll take an umbrella

If not, I’ll take a cap.

In this case, in addition to having an action if the condition is met, we have an action to perform if the condition is not met.

programacion-condicional-doble

We call this type of structure IF-ELSE, and seen in code it would be something like this.

if it rains:
    // take umbrella
else:
    // take cap

Types of conditionals

In programming, there are usually these and other types of conditionals. The most common ones are:

Each of them has its usefulness and use case. We must know them all as they are a fundamental part of any program.