8 Conditional and Logical Operators

Conditional and logical operators[1] are used to make statements that can be evaluated (worked out) to be True or False.

True and False are keywords in Python[3] 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[2] 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[4] 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[2] 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[5] or an item is in a list

There is additional information on Operators on W3 Schools

Terms definitions
1. logical operators. These are pieces of code or digital objects that help a system understand the difference between different options.
2. condition. A statement that a program checks to see if it is true or false. If true, an action is taken. Otherwise, the action is ignored.
3. Python. A type of programming language. It is one of many high-level, general-purpose programming languages. It was first released in 1991
4. need. An identified requirement of a person, group, or environment. A need is identified from an issue and sits within a context. Technological practice can be undertaken in an attempt to meet an identified need.
5. string. A data type used to store text. Often enclosed in “” or ”