Conditional and logical operators are used to make statements that can be evaluated (worked out) to be True or False.
True and False are keywords in Python to store true and false values.
These are used to allow branching and different paths for our programs to take.
These are often used in if statements and loops such as while and for.
Each of these sections of code (if, while, for) require a condition to be met for that section of code to run.
If the condition is not met the code block will be skipped.
To do this we need to be able to write code that can be evaluated to be true or false.
There are certain conditional operators that we use to help us with this.
- < less than
- <= less than or equal to
- > greater than
- >= greater than or equal to
- == equal to
- != not equal to
Below are some examples of the results of different conditions
|4 < 5||True|
|4 < 4||False|
|5 < 4||False|
|4 <= 5||True|
|4 <= 4||True|
|5 <= 4||False|
|4 > 5||False|
|4 > 4||False|
|5 > 4||True|
|4 >= 5||False|
|4 >= 4||True|
|5 >= 4||True|
|4 == 4||True|
|4 == 5||False|
|4 != 4||False|
|4 != 5||True|
Despite all of these examples using numbers you can use other values such as strings. Note that Strings only really make sense for comparing if they are equal or not.
Often you want to combine multiple conditions together.
To do this we use the logical operators and, or and not.
- and returns true if both statements are true
- or returns true of one of the statements is true
- not switches the result so a true statement becomes false and vice versa.
|Logical Operator Example||Result|
|true and true||True|
|true and false||False|
|false and true||False|
|false and false||False|
|true or true||True|
|true or false||True|
|false or true||True|
|false or false||False|
Other keywords that exist in Python are:
- is – this is used to check if something matches another item exactly
- in – this is used to check if an item is in a list or present. You might use this to check if a letter is in a string or an item is in a list
There is additional information on Operators on W3 Schools