Conditional expressions are our way of asking the program a question. When you write one in your program and run it, the program will decide if the answer to the question is true or false.
A conditional expression will typically contain three parts.
- A left operand
- A conditional operator
- A right operand
A small example of this is shown in the image below. The left operand being the 5, the conditional operator being the “>” symbol and the right operand being the 3. This just asks a very simple question - Is 5 greater than 3?
In: 5>3 Out: True
When that code is run, you can see in the output block that it was true. We can also store this inside a variable like so
In : ExpressionVariable = 5>3 print(ExpressionVariable) True
But ‘Greater Than’ isn’t the only conditional operator, there are many more…
|<=||Less Than or Equal to||
|>=||Greater Than or Equal to||
The Equals operator is used to check if the given operands are the same. In the example below, we have two variables,
Y which have each been assigned a number.
If we were to use the Equals operator to check if our
X variable was equal to
5, our conditional expression would resolve to
True. A few more examples are shown after being run in Jupyter Notebook below.
In : X = 5 Y = 10 In: print(X == 5) print(X == 6) print(X == Y) True False False
Not Equals (!=)
The Not Equals operator is the exact opposite of the Equals operator. It is used to check if the given operands are not the same and will resolve to
True if not equal to each other.
In : X = 5 Y = 10 In: print(X != 10) print(X != 5) print(X != Y) True False True
Less Than (<)
The Less Than operator is used to check if the Left operand is less than the Right operand.
In : X = 5 Y = 10 In: print(1 < 2) print(X < 3) print(X < Y) True False True
Greater Than (>)
The ‘Greater Than’ operator is used to check if the Left operand is greater than the Right operand.
In : X = 5 Y = 10 In: print(10 > 2) print(X > 15) print(X > Y) True False False
Less/Greater Than or Equal to (>=, <=)
These operators do the exact same job as the Less Than and Greater Than Operators (
<), but they also check if the value of the left operand in the conditional expression is equal to the right operand.
In : X = 5 Y = 10 In: print(X <= 5) print(X <= 6) print(X >= Y) True True False
We can also do calculations in our conditional expression on the fly. In the below example we are checking if the sum of X and Y is equal to 15.
In : X = 5 Y = 10 In: print((X + Y) == 15)
Time to put this into practice.
Look at the following examples and decide whether they would be True or False if you were to run them in your program.
5 > 3
19 < 10
(10 / 5) == 2
(30 * 2) + 3 > 70
"False" != False
True == 1
© Coventry University. CC BY-NC 4.0