Python if not example

Python If with NOT Operator

We can use logical not operator with Python IF condition. The statements inside if block execute only if the value(boolean) is False or if the value(collection) is not empty.

Syntax

The syntax of Python If statement with NOT logical operator is

where the value could be of type boolean, string, list, dict, set, etc.

If value is of boolean type, then NOT acts a negation operator. If value is False, not value would be True, and the statement(s) in if-block will execute. If value is True, not value would be False, and the statement(s) in if-block will not execute.

If value is of type string, then statement(s) in if-block will execute if string is empty.

If value is of type list, then statement(s) in if-block will execute if list is empty. The same explanation holds correct for value of other collection datatypes: dict, set and tuple.

Читайте также:  Wordpress главная страница index php

In summary, we can use if not expression to conditionally execute a block of statements only if the value is not empty or not False.

Examples

1. if not with Boolean

In this example, we will use Python not logical operator in the boolean expression of Python IF.

Python Program

a = False if not a: print('a is false.')

2. if not with String

In this example, we will use Python if not expression to print the string only if the string is not empty.

Python Program

string_1 = '' if not string_1: print('String is empty.') else: print(string_1)

3. if not with List

In this example, we will use Python if not expression to print the list only if the list is not empty.

Python Program

a = [] if not a: print('List is empty.') else: print(a)

4. if not with Dictionary

In this example, we will use Python if not expression to print the dictionary only if the dictionary is not empty.

Python Program

a = dict(<>) if not a: print('Dictionary is empty.') else: print(a)

5. if not with Set

In this example, we will use Python if not expression to print the set, only if the set is not empty.

Python Program

a = set(<>) if not a: print('Set is empty.') else: print(a)

6. if not with Tuple

In this example, we will use Python if not expression to print the tuple, only if the tuple is not empty.

Python Program

a = tuple() if not a: print('Tuple is empty.') else: print(a)

Summary

In this tutorial of Python Examples, we learned to use not logical operator along with if conditional statement, with the help of well detailed examples programs.

Источник

How to use the if not Python statement?

In this short tutorial, we learn about the ‘if not’ Python condition statement. We also look at its various use cases along with the code.

Before we look at the if not Python statement, we will first give a small brief about the ‘Not’ operator in Python. In case you are not familiar with it, do read along. Else, please feel free to jump straight to the Solution.

Table of Contents — If not Python

Not Operator — Recap

Similar to ‘and’ & ‘or’ the ‘not’ operator is another logical operator in Python. This operator returns True if the statement is not true and vice versa. Hence the ‘Not’ operation is commonly used along with the ‘if’ statement.

Based on this functionality, the Not operator is used in two major use cases. The first case is to check if an element is not in a string or any other iterable and the second is to check if a condition is not met. In this article, we look at the latter.

Although both these requirements can be met using other methods, using the ‘not’ operator improves the readability of your code.

Why do we use the ‘If not’ Python statement?

When it comes to checking if a particular condition is not met, the ‘if not’ Python operator is used extensively in two areas.

Let us look at real-world examples of both these cases. For the first case let us assume that you have an iterable; a list that contains information of all the blocked users on your application. When a user attempts to sign in, your code could check if the user is not in the Python list. In a conventional ‘if’ statement this logic would have to be written inside the ‘else’ statement however the not operator negates the output and outputs the inverse. Thereby increasing readability by allowing the user to write the logic under the ‘if’ statement.

For the second case, empty variables or items return falsy values, and similar to the previous use case, a normal ‘if’ statement would have logic within the ‘else’ statement. The ‘Not’ operator negates the output again making the code more readable.

Code and Explanation:

Using the ‘if not’ Python statement to check if it negates the output of an ‘if’ statement.

number = 2 if not number > 3: print('number is greater than 3') else: print('number is not greater than 3') #Output - number is greater than 3 

As you can see, the code under the ‘if’ block was returned although the condition returned false. This is because the ‘not’ operator negated its value.

Similarly, the code to check if an iterable is empty using the ‘if not’ Python statement is as follows.

List_1 = [] if not List_1: print('List_1 is empty.') else: print(List_1) #Output - List_1 is empty 

The ‘if not’ Python code can be used to check if a string, dictionary, set, and even a tuple.

If not Python — Limitations and Caveats:

  • There are no major limitations while using the ‘Not’ operator, however, since the logic is inverted I would recommend practicing the ‘if not’ Python statement a few times before you actually start using it in your code.

Источник

Используйте условие if not в Python

Используйте условие if not в Python

  1. Истинные и ложные значения в Python
  2. Примеры условия if not в Python

Оператор if комбинируется с логическим оператором not , чтобы оценить, не произошло ли условие. В этой статье объясняется, как использовать условие if not в Python.

Вот блок кода, демонстрирующий это состояние.

if not a_condition:  block_of_code_to_execute_if_condition_is_false 

В приведенном выше случае код block_of_code_to_execute_if_condition_is_false будет выполнен успешно, если результатом a_condition будет False .

Истинные и ложные значения в Python

  • Числовые нулевые значения, такие как 0 , 0L , 0.0 .
  • Пустые последовательности, такие как:
    • пустой список []
    • пустой словарь <>
    • пустая строка »
    • пустой кортеж
    • пустой набор
    • объект None

    Примеры условия if not в Python

    Вот несколько примеров, которые помогут вам понять, как if not используется в Python.

    Использование логических значений

    if not False:  print ("not of False is True.") if not True:  print ("not of True is False.") 

    Использование числового значения

    Например, такие значения, как 0 , 0L , 0.0 связаны со значением False .

    if not 0:  print ("not of 0 is True.") if not 1:  print ("not of 1 is False.") 

    Использование Списка ценностей

    if not []:  print ("An empty list is false. Not of false =true") if not [1,2,3]:  print ("A non-empty list is true. Not of true =false") 
    An empty list is false. Not of false =true 

    Использование словарных значений

    if not <>:  print ("An empty dictionary dict is false. Not of false =true") if not   "vehicle": "Car",  "wheels": "4",  "year": 1998  >:  print ("A non-empty dictionary dict is true. Not of true =false") 
    An empty dictionary dict is false. Not of false =true 

    Использование строки значений

    if not "":  print ("An empty string is false. Not of false =true") if not "a string here":  print ("A non-empty string is true. Not of true =false") 
    An empty string is false. Not of false =true 

    Использование значения None :

    if not None:  print ("None is false. Not of false =true") 
    None is false. Not of false =true 

    Использование set ценностей:

     dictvar = <>  print("The empty dict is of type", type(dictvar))  setvar= set(dictvar)  print("The empty set is of type",type(setvar))  if not setvar:  print ("An empty set is false. Not of false =true") 
     The empty dict is of type  The empty set is of type  An empty dictionary dict is false. Not of false =true 

    Использование tuple значений

    Пустой кортеж связан со значением False .

    if not ():  print ("1-An empty tuple is false. Not of false =true") if not tuple():  print ("2-An empty tuple is false. Not of false =true") 
    1-An empty tuple is false. Not of false =true 2-An empty tuple is false. Not of false =true 

    Copyright © 2023. All right reserved

    Источник

Оцените статью