And or operations in python

Boolean operators in Python (and, or, not)

Python provides Boolean operators, and , or , not . For example, they are used to handle multiple conditions in the if statement.

See the following article for bitwise operations on each bit of an integer instead of Boolean operations of True and False . Use & and | instead of and and or .

See the following article for the if statement.

and (Logical conjunction)

and returns the logical conjunction of two values.

print(True and True) # True print(True and False) # False print(False and True) # False print(False and False) # False 

In practice, these operators are often used with comparison operators ( < , >, etc.) for conditional expressions rather than with True or False . The same applies to or and not , which will be described later.

a = 10 print(0  a) # True print(a  100) # True print(0  a and a  100) # True 

Multiple comparisons can be chained as follows.

or (Logical disjunction)

or returns the logical disjunction of two values.

print(True or True) # True print(True or False) # True print(False or True) # True print(False or False) # False 

not (Negation)

not returns the negation of the value. True and False are inverted.

print(not True) # False print(not False) # True 

Precedence of and , or , not operators

The precedence of Boolean operators is not > and > or ( not is the highest precedence).

In the sample code below, the first expression is equivalent to the second one.

It doesn’t matter if there are extra parentheses () , so in cases like this example, the parentheses may make it easier to understand the meaning of the expression.

print(True or True and False) # True print(True or (True and False)) # True 

If you want to calculate or before and , use parentheses () for or .

print((True or True) and False) # False 

Comparison operators such as < , >have higher precedence than not , and , or , so parentheses () are not required for each comparison, as in the example above.

print(0  a and a  100) # True 

See the official documentation below for a summary of operator precedence in Python.

Boolean operations for objects that are not bool type

The Boolean operators and , or , not handle not only bool type ( True , False ) but also numbers, strings, lists, etc.

In Python, the following objects are considered false in Boolean operations.

  • constants defined to be false: None and False
  • zero of any numeric type: 0 , 0.0 , 0j , Decimal(0) , Fraction(0, 1)
  • empty sequences and collections: » , () , [] , <> , set() , range(0)

Everything else is considered true.

You can get the Boolean value of an object with the bool() function. Note that the strings ‘0’ and ‘False’ are considered true.

print(bool(10)) # True print(bool(0)) # False print(bool('')) # False print(bool('0')) # True print(bool('False')) # True print(bool([])) # False print(bool([False])) # True 

Use distutils.util.strtobool() to treat the strings ‘0’ and ‘False’ as false. See the following article.

and , or does NOT always return bool type

and , or , and not for integers:

x = 10 # True y = 0 # False print(x and y) # 0 print(x or y) # 10 print(not x) # False 

As seen in the example above, in Python, and and or do not always return bool ( True or False ); they return the left or right values. not always returns bool ( True or False ).

The same is true for other types such as strings, lists, etc.

The definitions of the return values of and and or are as follows.

The expression x and y first evaluates x ; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x ; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. 6. Expressions — Boolean operations — Python 3.11.3 documentation

When the left and right values are either true and false or false and true, the return value is straightforward. However, when both values are true or both are false, the return value depends on the order of evaluation.

When used as a conditional expression in an if statement, the result is evaluated as a Boolean value, so there is no need to worry. However, be cautious when using the return value in subsequent operations.

x = 10 # True y = 100 # True print(x and y) # 100 print(y and x) # 10 print(x or y) # 10 print(y or x) # 100 
x = 0 # False y = 0.0 # False print(x and y) # 0 print(y and x) # 0.0 print(x or y) # 0.0 print(y or x) # 0 print(bool(x and y)) # False 

If you want to receive the result as True or False , use bool() as in the last example.

The return values of and and or are summarized in the table below.

x y x and y x or y
true false y x
false true x y
true true y x
false false x y

Short-circuit evaluation

As you can see from the table above, if x is false in x and y or if x is true in x or y , the return value is always x . In such cases, y is not evaluated.

Note that if you call a function or method on the right side of and and or , they may not be executed depending on the result on the left side.

def test(): print('function is called') return True print(True and test()) # function is called # True print(False and test()) # False print(True or test()) # True print(False or test()) # function is called # True 

Источник

Как использовать операторы AND, OR и NOT в IF в Python

Вы можете объединить несколько условий в одно выражение в условных операторах в Python, таких как if, if-else и elif. Это позволяет избежать ненужного написания нескольких вложенных операторов if.

В следующих примерах мы увидим, как мы можем использовать логический оператор AND для формирования составного логического выражения.

Пример 1: с оператором If

В следующем примере мы узнаем, как использовать логический оператор and в операторе If, чтобы объединить два логических условия для формирования составного выражения.

Чтобы продемонстрировать преимущества команды and, мы сначала напишем вложенный оператор if, а затем простой оператор, где он реализует ту же функциональность, что и вложенный оператор.

a = 5 b = 2 #nested if if a==5: if b>0: print('a is 5 and',b,'is greater than zero.') #or you can combine the conditions as if a==5 and b>0: print('a is 5 and',b,'is greater than zero.')

Здесь наш вариант использования состоит в том, что мы должны напечатать сообщение, когда a равно 5, а b больше 0. Без использования команды and мы можем написать только if, чтобы запрограммировать функциональность. Когда мы использовали логический оператор и обычный мы могли сократить количество if до одного.

a is 5 and b is greater than zero. a is 5 and b is greater than zero.

Пример 2: с оператором If-Else

В следующем примере мы будем использовать оператор and для объединения двух основных условных выражений в логическое выражение оператора If-Else.

a = 3 b = 2 if a==5 and b>0: print('a is 5 and',b,'is greater than zero.') else: print('a is not 5 or',b,'is not greater than zero.')
a is not 5 or 2 is not greater than zero.

Пример 3: с оператором elif

В следующем примере мы будем использовать функцию and для объединения двух основных условных выражений в логическое выражение оператора elif.

Мы узнали, как использовать логический оператор and с условными операторами: if, if-else и elif с хорошо подробными примерами.

Оператор OR

Вы можете объединить несколько условий в одно выражение в операторах if, If-Else или Elif.

В следующих примерах мы увидим, как мы можем использовать OR для формирования составного логического выражения.

Логический оператор OR возвращает True, если один из двух предоставленных ему операндов имеет значение true.

Пример 1: с оператором If

В следующем примере мы узнаем, как использовать OR для соединения двух логических условий для формирования логического выражения.

today = 'Saturday' if today=='Sunday' or today=='Saturday': print('Today is off. Rest at home.')
Today is off. Rest at home.

Пример 2: с оператором If-Else

В следующем примере мы будем использовать оператор OR для объединения двух основных условных выражений в логическое выражение.

today = 'Wednesday' if today=='Sunday' or today=='Saturday': print('Today is off. Rest at home.') else: print('Go to work.')

Пример 3: с оператором elif

В следующем примере мы будем использовать OR для объединения двух основных условных выражений в логическое выражение операторов elif.

today = 'Sunday' if today=='Monday': print('Your weekend is over. Go to work.') elif today=='Sunday' or today=='Saturday': print('Today is off.') else: print('Go to work.')

Мы узнали, как использовать оператор OR логический оператор с условным оператором Python: if, if-else и elif с хорошо подробными примерами.

Оператор NOT

Мы можем использовать логический оператор not с условием IF. Операторы внутри блока if выполняются только в том случае, если значение (логическое) равно False или если значение (коллекция) не пусто.

Синтаксис

Где, значение может иметь тип boolean, string, list, dict, set и т.д.

Если значение имеет логический тип, NOT действует как оператор отрицания. Если значение равно False, значение not будет True, и операторы в блоке if будут выполняться. Если value равно True, not value будет False, и операторы в блоке if не будут выполняться.

Если значение имеет строковый тип, то операторы в блоке if будут выполняться, если строка пуста.

Если значение имеет тип list, тогда операторы в блоке if будут выполняться, если список пуст. Такое же объяснение справедливо для значений других типов данных коллекции: dict, set и tuple.

Таким образом, мы можем использовать if not expression для условного выполнения блока операторов, только если значение не пустое или не False.

Пример 4

В этом примере мы будем использовать нелогический оператор NOT в логическом выражении IF.

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

Пример 5: для печати строки

В этом примере мы будем использовать if not expression для печати строки, только если строка не пуста.

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

Пример 6: для печати списка

В этом примере мы будем использовать if not expression для печати списка только в том случае, если список не пуст.

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

Пример 7: для печати словаря

В этом примере мы будем использовать if not expression для печати словаря, только если словарь не пуст.

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

Пример 8: для печати набора

В этом примере мы будем использовать if not expression для печати набора, только если набор не пуст.

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

Пример 9: для печати кортежа

В этом примере мы будем использовать if not expression для печати кортежа, только если кортеж не пуст.

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

Мы научились использовать оператор not вместе с условным оператором if с помощью примеров программ.

Источник

Читайте также:  Время обработки запроса php
Оцените статью