Course 2 – For loop, and, or

In the previous course we discussed about the conditional.

A few things to mention about them:

if / elseif / else

If in the code we have two ifs, both of the conditions will be checked.

Here, conditions are independent.

If we have if-elseif:

If it’s raining we take an umbrella, otherwise, if it’s snowing, we take a jacket – but never both.

If the first condition is valid, the second one will not be executed (note the otherwise)

Therefore, we use two ifs if both conditionals are independent, and if/elseif when they are related in some way.

We enter the elseif statement if the value is less than 20.

Because we are here, we know that the condition from above was not fulfilled – so value is higher than 10.

When we use if and elseif – without a final else – we can understand that there are situations in which the code will not be executed.

If the code looks like this:

We see that we have an if-elseif, but we already go through the whole set of values possible for that data.

Here, there are two conditions that are validated: if value > 0, and if value <= 0 – but we can simplify it and use just an if-else, validating only one condition.

for loop

The for instruction looks like this:

This will print the values from 0 up to 5 (but without 5)

AND operator

If we want to validate multiple conditions at the same time, we use and.

The result is true if both conditions are true.

This is equivalent to:

Example:

We do not want to go to the vet if we don’t have a cat, but also if we have a cat but the cat is not sick.

OR operator

For this operator, the result is true if only one of the conditions is valid.

Example:

In this case, if at least one of the conditions is valid, we will take a jacket 🙂

break and continue

Break and continue are instructions that can be used in loops such as for or while, to influence how the code will behave.

Break will completely take us out of the loop, whereas continue will not execute any lines that are below of it, and go back up to the condition check.

Output:

  • i = 3
  • i = 4
  • i = 5
  • i = 6

You may also like...