Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.
We will start with the
if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.
With this code, we have the variable grade and are giving it the integer value of
70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal (
>= ) to 65. If it does meet this condition, we are telling the program to print out the string Passing Grade.
It is likely that we will want the program to do something even when an
if statement evaluates to false. To do this, we will add an
else statement to the grade condition above that is constructed like this:
Since the grade variable above has the value of 60, the
if statement evaluates as false, so the program will not print out Passing Grade. The else statement that follows tells the program to print out the other else option, as you can see in the following:
In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an elif statement, which is written in Python as
elif or else if statement looks like the
if statement and will evaluate another condition.
Let me show you an example for a bank account program:
- The balance is below 0
- The balance is equal to 0
- The balance is above 0
The elif statement, more or less, just adds another option to your condition.