A condition
is an operation used in programs to see if something is true or not. These conditionals
help you doing ac action whenever they are true. During this post I will guide
you on how to use them properly for the creation of a program:
First of
all we need to understand which ones are these conditionals.
The first
one is called IF. We place it in the middle of out code to see if a condition
is true or false. We can only place it once, the rest of the conditions will be
evaluated by a different function.
The second
one is ELIF. This one can be used to evaluate many conditions along the same
IF. This function can be used as many times as you want, as long as you state the word "elif" followed by the statement you want to evalute.
ELSE is the
last conditional. It is use to stablish what will happen in case none of the
conditions above is true.
Now, we are
creating a program that will evaluate a given number and show if it´s positive,
negative or 0.
So we start
by asking the user for a number.
How we
start with our first condition; if the number is greater than zero, then it´s a
positive number. So, for this we need to type if followed by the condition that
would be x>0. At the end of the line we place a colon ( : ).
After this,
we need the program to let the user know that the number is positive, se we create
an output. This output need to be intended to show that is the action the
computer should do in case the condition is true.
If this
condition is not true, then it means that the number is zero or a negative
number. To differentiate if this number is zero or negative we will need
another conditional. But as we explained before, this conditional cannot be an
IF conditional, but an ELIF.
An ELIF
conditional works just an IF conditional: you place the word “elif” followed by
the condition “x==0” and ending with a colon. Now the condition we will be
evaluating is if the number is equal to zero. (It is necessary to place two
equal signs to evaluate)
If none of
this conditions are true, then we know that the number given by the user if not
zero or greater than zero; therefore, this number is lower than zero. We know
that the only numbers that are lower than zero are negative numbers.
Based on
the previous reasoning, if this numbers fails to be true in both conditionals,
then it is a negative number.
Now we know
we don´t need to evaluate in any other condition so we can use the conditional ELSE.
For this, we only write the word “else” followed by a colon. That, we just need
to type the action we want the computer to do.
And this is
what will happen when you run this program: