If Statements
Written by Anish Ahuja and Harnoor Chima (8/2/2020)
Last updated
Written by Anish Ahuja and Harnoor Chima (8/2/2020)
Last updated
Comparison operators are used, as is evident in the name, to compare 2 values in condition statements. There are multiple types of comparison operators. When a comparison operator is performed, the computer checks to see if the comparison is True or False. If it is True, the following operation is performed. If False, the operation is skipped. This is a Boolean check being performed here.
For this example, assume a = 5 and b = 10
These comparison operators are commonly used in if statements so you can determine if a certain set of conditions is true, if they are true you can initiate an appropriate response.
Let's break down how to write an if statement, following if
you write the condition you are checking for in this case it would be x is equal to 9. Then we put a colon and move to the next line, this is where indentation comes in, press tab to indent four spaces and write the response if the condition is met. Indentation is very important in python because it tells the interpreter what our code is being applied to. In this case x
is equal to 9 so the statement "x is equal to 9" is printed.
Else if is used when you want to check for more than one condition in an if statement.
In this example, y
is equal to 5 and our first test sees if y
is less than 2 which is not true in this case so it moves on to the next condition. This condition checks if y
is greater than 4 which is true so it prints the statement, "y is greater than 4."
However, what if y
is not less than 2 or greater than 4? This is a situation in which else
would be used. You can use else
to make sure that your program gives a response if the given conditions are not actually met.
In this situation neither of the two conditions are met so the program automatically moves on to the else response and prints the statement, "z is in between 7 and 13."
Here's an example of these operators in action:
If using a Boolean, it is unnecessary to write Boolean == True in the condition. Instead, simply writing the variable name means True, and entering not
before the name means False
Comparison Operators are important as they allow you to write if statements, which are frequently used in programming.
Comparison Operator
Meaning
Example
==
Checks to see if 2 values are equal
a==b is False
!=
Checks if 2 values are not equal to each other
a!=b is True
>
Checks if 1 value is greater than the other
a>b is False
<
Checks if 1 value is less than the other
a<b is True
>=
Checks if 1 value is greater than or equal to the other
a>=b is False
<=
Checks if 1 value is less than or equal to the other
a<=b is True