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?
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:
Here is the output:
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:
Here is the output.=:
Remember to always use parentheses to group your conditions explicitly, especially when you combine if not with other logical operators like and and or.
Here is the output:
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”.
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:
Here is the output:
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:
Here is the output:
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:
Here is the output:
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>:
<expression>
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:
Here is the output:
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:
Here is the output:
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:
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:
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:
Here is the output:
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:
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!’:
Here is the output:
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 “if not” with lists: Python if not can be used to check if an item is not in a list. Consider the example below:
In the code snippet above, it verifies if mango is not an element of my_list.
Here is the output:
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:
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.
Here is the output:
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:
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.
Here is the output:
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:
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.
Here is the output:
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:
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.
Here is the output:
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:
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:
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:
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: