When implementing a function in your Kodika project, you may find yourself needing to implement different actions depending on a true or false condition. The way to implement this kind of logic is using the if-else if-else statement.
To explore the if- else if - else statement let's create a "test" function, that has an "name" argument. We will add a "lastName" model variable. For our example, we will implement a logic where if the "name" argument is "Anna", then we will set the "lastName to "Papadopoulou". However, if the "name" argument is "Helen", then we will set "lastName" variable to "Papadaki". If the "name" is neither "Anna" or "Helen", then we will set "lastName" to "Unknown".
This is the implementation of our example function. If Condition 1 is true, then Action 1 will be executed and the other two actions won't. If the Condition 1 is false, Action 1 won't be executed, and the Condition 2 will be examined. If it is true, then Action 2 will be executed. In the case that both Condition 1 and Condition 2 are false, then Action 3 will be executed, since it is in the Else block. If there was no Else in our if statement, then there no actions would be executed.
To sum up, an if - else if - else statement:
- has one "if" condition.
- can have as many "else if" conditions as you wish.
- can have zero to one "else" condition.