Python If Not: Logical Operator Explained

by | Python

Python is a widely used programming language, loved for its simplicity. As you gain experience, you’ll notice the importance of conditionals. The if not statement, in particular, is like a secret handshake between programmers you really need to learn.

In Python, the “if not” logical operator is used to test the opposite of a condition, where the code inside the block will be executed only if the condition evaluates to False. It’s the opposite of the “if” statement, which checks if a condition is true.

In this article, we’re going to break down the concept of “if not” in Python into two parts: “if” and “not.” First, we’ll explore these ideas as they relate to conditional statements (“if”) and boolean operators (“not”), then we’ll see some practical examples.

Sound good? Let’s get started!

What Does the Syntax for “If Not” in Python Look Like?

Python If not

When working with Python, you may encounter situations where you want to check if a specific condition is not met. The if not is here to achieve this task without having to write complex logical expressions.

Here’s an example using if not to check if a number is NOT greater than another:

Example of if not to check if a number is not greater than another

Here is the output:

Output of the code usage of the Python if not

In the above example, the if not statement checks from statements inside the if block, if a is not greater than b, and if the condition is true, it prints the string.

Additionally, you can use if not in combination with Python’s in and not in operators to perform membership tests. Here’s a simple example:

Using "if not" with python's "in" and "not in" operators

Here is the output.=:

Output of the code

Remember to always use parentheses to group your conditions explicitly, especially when you combine if not with other logical operators like and and or.

Combining "if not" with "or"

Here is the output:

Output of the code

We’ve explored the if not statement in Python, and by using it, you can test the opposite of a condition. If not includes both:

  • Conditional statement (if)
  • Boolean operators (not)

Before delving into if not examples, first, let’s discover the boolean operators (not) and conditional if statements consecutively.

What Are the 3 Boolean Operators in Python?

Remember how we split Python if not into if and not in the intro? Just like in a cool squad, ‘not’ is a Boolean operator that hangs out with two other buddies. In this section, we’ll get to know all of them.

Boolean operators, also known as logical operators, help us make decisions based on different conditions in programming. These operators include “and”, “or”, and “not”.

Boolean operators in Python

1. Not Operator

In Python, the not logical operator allows you to invert the truth value of Boolean expressions and objects. It’s often used in control structures like if statements and while loops.

Take a look at the following example:

How the "not" operator works

Here is the output:

Output of the code

As you can see from the code block above, the not logical operator negates the truth value of a and assigns it to the value of the variable b.

2. And Operator

The and operator is used to combine two Boolean expressions, returning True if both expressions are true, and False otherwise.

Here’s an example:

Example of "and" operator for particular condition

Here is the output:

Output of the code

As you can see from the code block above, since y is False, the result of x return true and y is False.

3. Or Operator

Similar to the and operator, the or operator also combines two Boolean expressions. It returns the boolean value True if at least one of the expressions is true, and will return False if both expressions are false.

Consider this example:

Example of "or" python operator

Here is the output:

Output of the code: operator returns true

Here, as x is True, the result of x or y is True.

When working with Boolean operators, remember these basic rules:

  • True and True returns True
  • True and False returns False
  • False and True returns False
  • False and False returns False
  • True or True returns True
  • True or False returns True
  • False or True returns True
  • False or False returns False

By using these operators, you can create more complex conditions, variables, and expressions in your Python code. Before looking at Python if not examples, let’s understand conditional statements too.

What Are Conditional Statements in Python?

So we already split Python if not into two parts — Boolean operators (“not”) and conditional statements (“if”). We’ve covered the Boolean part, so now it’s time to shine the spotlight on conditional statements.

When working with conditional statements, you will typically make use of the :

  • if
  • else
  • elif

These statements enable your code to make decisions based on the evaluation of boolean expressions.

A basic if statement follows a simple structure:

if <condition>:

Here, <condition> is a boolean expression — its value can be True or False. If the condition evaluates to True, the <expression> within the block will be executed.

When you want to reverse the result of the condition in an if statement, you can use the not keyword. Here’s an example:

Example of "if not" in python

Here is the output:

Output of the code

In the code block above, the condition checks whether a is not greater than b. If the condition is True, it prints the message accordingly.

The not keyword is effective when you need to manipulate and evaluate the outcome of boolean expressions and enhance the logic of the expression in your program.

Consider using the elif and else keywords when you need to implement multiple conditions:

Example of "elif" keyword in python

Here is the output:

Output of elif

In the code block above, the Python program checks each condition sequentially. If the if statement evaluates to False, it moves on to the elif statement. If that too evaluates to False, the code executes the else statement.

Remember to structure your statements with proper indentation and use a combination of if, not, else, and elif keywords to achieve the desired logic.

Now that we’ve gone over both conditional statements and the not operator, let’s take a look at what types of Python data types work with if not in the next section.

How to Use Python “If Not” Statements with Different Data Types

In this section, we’ll cover Python built-in data types first. After each built-in data type, you’ll find the Python if not examples.

Also if you want to test your skills afterward, check out the video below to learn how to load sample datasets in Python:

What are Python Data types

1. Numbers

You can work with different types of numeric data, including integers, floats, and complex numbers. Integers are whole numbers, while floats represent decimal numbers. Complex numbers consist of a real and an imaginary part.

For example:

Examples of integers, floats, and complex numbers

Python “if not” with numbers: Python’s if not can be used to check if a condition is not met. In this example, it verifies if ‘number’ is not equal to 10:

Using python if not with numbers

Here is the output:

Output of the code for a true value

The code snippet above prints a statement if the variable number is not equal to 10.

2. Strings

Strings store sequences of characters, making them ideal for text manipulation. You can create strings in Python using either single quotes or double quotes:

Examples of non-empty string

Python “if not” with strings: Python if not can check if a string variable doesn’t match a certain string. Here, it checks if the greeting is not ‘Hello, World!’:

Code to print if not with strings

Here is the output:

Output of the code

3. Lists

Lists in Python are ordered and mutable, allowing you to store and modify a collection of items. You create a list using square brackets and separate the elements with commas:

Python list if file exists

Python “if not” with lists: Python if not can be used to check if an item is not in a list. Consider the example below:

If not with a list in Python

In the code snippet above, it verifies if mango is not an element of my_list.

Here is the output:

Output of the code

4. Tuples

Similar to lists, tuples store ordered collections of items. The main difference is that tuples are immutable, meaning their elements can’t be changed once assigned. You create tuples using parentheses:

Creating a tuple in python

Python “if not” with tuples: Python if not can check if an item is not present in a tuple. Here, it verifies that mango is not a member of my_tuple.

A tuple containing three fruits
Tuple working with if not

Here is the output:

Output of the code

5. Dictionaries

Dictionaries are unordered and mutable collections of key-value pairs. They are used to store data that can be easily retrieved using unique keys.

You create dictionaries using curly braces:

Dictionary in python with key-value pairs

Python “if not” with dictionaries: Python if not can check whether a key is not in a dictionary. In this case, it verifies if key4 is not a key in my_dict.

Python if not with a dictionary

Here is the output:

Output of code example

6. Sets

Sets are unordered collections of unique elements. They are useful for performing operations like union, intersection, and difference. You create sets using curly braces or the set() function:

A set containing fruit

Python “if not” with sets: Python if not can check whether a set contains a specific item. If the item is not in the set, if not will return True. In this example, it checks if mango is not a member of my_set.

Python set interacting with if not

Here is the output:

Output of the code

7. Range

The range data type represents a sequence of numbers. It is commonly used in for loops to repeat actions a specific number of times. You can create a range with the range() function:

Range in python

Python “if not” with range: Python if not can check whether a particular number is not in a range. Here, it checks if 11 is not included in number_range.

Python if not interacting with a range

Here is the output:

Output of the code

Final Thoughts

In this article, we explored Python’s if not with a wide range of use cases. First, we split if not in Python into ‘if’ (a conditional statement) and ‘not’ (a boolean operator). We went over the boolean operators not, and, and or. Then, we continued discovering if statements, such as if, elif, and else.

After understanding the fundamentals, we covered the interactions of different data types with ‘if not’. It can work with numbers, strings, lists, tuples, dictionaries, sets, and ranges. This makes if not a powerful and useful tool for coders.

If not is a perfect example of the simplicity and readability of Python. It provides a straightforward way to handle negative conditions. As you continue to explore Python, you’ll find that these seemingly small tools can be combined in creative ways to solve complex problems. So don’t underestimate the power of these building blocks!

Frequently Asked Questions

Can I use ‘if not’ in Python?

Yes, if not is a common expression in Python used to check if a condition is False. If the condition is False, the code within the if not block will execute.

Here’s an example:

Example of if not in python

What is == and != in Python?

== is a comparison operator in Python that checks if two values are equal. If they are, it returns True; otherwise, it returns False. != is also a comparison operator that does the exact opposite: it checks if two values are not equal.

Here’s an example:

Example of Python == and != operators

What is ‘if not var’ in Python?

if not var is a way to check if a variable is considered False in a boolean context. These might be values such as None, False, 0, or empty collections like [] or {}.

Here’s an example:

Example of if not var in python

How to do negation in Python?

Negation in Python is done using the not keyword. It negates the truth value of the condition that follows it. For example:

Negation in python
author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts