Python: 08 Conditional and Logical Operators

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.

Conditional Operators

There are certain conditional operators that we use to help us with this.

They are:

  • < 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

Condition ExampleResult
4 < 5True
4 < 4False
5 < 4False
4 <= 5True
4 <= 4True
5 <= 4False
4 > 5False
4 > 4False
5 > 4True
4 >= 5False
4 >= 4True
5 >= 4True
4 == 4True
4 == 5False
4 != 4False
4 != 5True

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.

Logical Operators

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 ExampleResult
true and trueTrue
true and falseFalse
false and trueFalse
false and falseFalse
true or trueTrue
true or falseTrue
false or trueTrue
false or falseFalse
not falseTrue
not trueFalse

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