Python and or brackets

Как использовать логические операторы and, or и not в Python — разбираем на примерах

Как использовать логические операторы and, or и not в Python — разбираем на примерах

В Python, логические операции используются для проверки и управления условиями выполнения программы.

В этой статье мы рассмотрим три основные логические операции в Python: and , or и not , и покажем, как они используются в различных сценариях.

Оператор and

Оператор and возвращает True только в том случае, если оба операнда являются истинными. В противном случае, если хотя бы один из операндов является ложным, оператор and возвращает False .

Рассмотрим следующий пример:

В этом примере, оператор and используется для проверки двух условий: x < y и y < z . Оба условия истинны, поэтому выводится сообщение y находится между x и z .

Давайте рассмотрим еще один пример, в котором оператор and используется для проверки нескольких условий:

x = 5 y = 10 z = 15 if x < y and y < z and z >10: print("z больше 10 и находится между x и y") #z больше 10 и находится между x и y

Здесь, оператор and используется для проверки трех условий: x < y , y < z и z >10 . Все три условия истинны, поэтому выводится сообщение z больше 10 и находится между x и y .

Оператор or

Оператор or возвращает True , если хотя бы один из операндов является истинным. Возвращается False только в том случае, если оба операнда являются ложными.

Рассмотрим следующий пример:

x = 5 y = 10 z = 15 if x > y or y > z: print("Не выполнено ни одно из условий")

В этом примере, оператор or используется для проверки двух условий: x > y и y > z . Оба условия ложны, поэтому сообщение от функции print() выводиться не будет.

Давайте рассмотрим еще один пример, в котором оператор or используется для проверки нескольких условий:

Оператор not

Оператор not возвращает логическое противоположение операнда. Если операнд истинный, оператор not возвращает False , а если операнд ложный, оператор not возвращает True .

Рассмотрим следующий пример:

x = 5 if not x == 10: print("x не равен 10") #x не равен 10

В этом примере, оператор not используется для проверки условия not x == 10 . Условие x == 10 является ложным, но оператор not инвертирует его, возвращая истину. Поэтому выводится сообщение x не равен 10 .

Давайте рассмотрим еще один пример, в котором оператор not используется для проверки того, содержится ли элемент в списке:

my_list = [1, 2, 3, 4, 5] if not 6 in my_list: print("6 не содержится в списке") #6 не содержится в списке

В этом примере, оператор not используется для проверки условия not 6 in my_list . Условие 6 in my_list ложно, поэтому оператор not возвращает истину и выводится сообщение 6 не содержится в списке .

В Python, логические операции могут использоваться не только в условных операторах if и while , но и в любом другом месте, где требуется проверка логического выражения.

Например, логические операции могут использоваться для определения, содержится ли элемент в списке:

my_list = [1, 2, 3, 4, 5] if 3 in my_list or 6 in my_list: print("Список содержит 3 или 6") #Список содержит 3 или 6

В этом примере, оператор or используется для проверки двух условий: 3 in my_list и 6 in my_list . Так как условие 3 in my_list истинно, то выводится сообщение Список содержит 3 или 6 .

В заключение, логические операции and , or и not являются важными инструментами для управления условиями выполнения программы в Python. Они позволяют комбинировать несколько условий в одно и определять, какой код должен быть выполнен в зависимости от результата проверки этих условий.

Источник

Boolean Operators in Python

Boolean Operators in Python

The operators such as not, and, or are used to perform logical operations in Python, with results of the operations involving them being returned in TRUE or FALSE. The not operator has the highest priority, followed by the operator and operator being the lowest in the order of the priority. The not operator has lower priority than non-Boolean operators. In Python programming language, the and as well as or operator is known as the short-circuit operators, are also called as Boolean operators

Web development, programming languages, Software testing & others

Boolean Values

The data types like Integer, Float, Double, String, etc., have the possibility to hold unlimited values; variables of type Boolean can have one of the two values: either TRUE or FALSE. In Python as a programming language, True and False values are represented as a string without enclosing them in double or single inverted commas, and they always start with the uppercase T and F.

bool_var = True bool_var True

In the above example, the variable named bool_var stores the Boolean value of True and when you print it out on the terminal, it shows True as the value.

By default, the Boolean value True is True in Python and False is False in Python.

true Traceback (most recent call last): File "", line 1, in NameError: name 'true' is not defined

The above example shows that the string spelled as true with a lowercase T is treated as a variable and not as a Boolean value.

True = 3+5 File "", line 1 SyntaxError: can't assign to keyword

This example shows that we cannot assign any values or expressions to the Boolean Values True or False in Python.

a = 1 bool(a) True a = 0 bool(a) False a = "some string" bool(a) True a = "" bool(a) False

From the above example, it can be seen that any value for a numeric datatype but 0 and any value for a string datatype but an empty string when typecasted to Boolean gives True value; otherwise, it treats it as False.

Different Boolean Operators in Python

Boolean Operators are the operators that operate on the Boolean values, and if it is applied on a non-Boolean value, then the value is first typecasted and then operated upon. These might also be regarded as the logical operators, and the final result of the Boolean operation is a Boolean value, True or False.

1. Comparison Operators

As described in the table below, there are six comparison operators, which evaluate the expression to a Boolean value.

Boolean Operators in Python-1.1

Now, let us consider an example each and see how they behave in Python Programming Language.

a = 1 a == 1 True a != 10 True a != 1 False a > 10 False a < 12 True a >= 1 True a 

So, you can see that with the integer value of 1 assigned to the variable ‘a’ and compared it with many other integral values, we get different Boolean results depending on the scenario. The value of ‘a’ can also be compared with other variables in a similar fashion.

2. Binary Boolean Operators

These operators are the ones that operate on two values which are both Boolean. The ‘and’ operator and the ‘or’ operator are the two binary Boolean operators that operate on some logic to give the Boolean value again. The standard Truth table for these two logical binary Boolean operators is as follows.

The truth table for the ‘and’ operator. Even if one value is false, then the whole expression is False.

Boolean Operators in Python-1.2

The truth table for the ‘or operator. Even if one value is true, then the whole expression is True.

truth table

Now, let’s see some example in Python. In Python, these operators are used by the keywords ‘and’ and ‘or’ for the ‘and’ logic and the ‘or’ logic, respectively.

a = True b = False a and b False a or b True

3. Not Operator

The ‘not’ operator is the logical Boolean Operator, which compliments the variable’s current Boolean value. That is, if the value is ‘true’, then the not operator will modify it to ‘false’ and vice versa. In Python, it is represented by the keyword ‘not’.

Let’s see the ‘not’ operator in action in Python.

a = True not a False not not not not a True

So, this is the way the ‘not’ operator works in Python.

Combination of Binary Boolean and Comparison Operators

Since the comparison operators evaluate to Boolean values and binary operators operate upon two Boolean values, we can have an expression that uses a combination of binary Boolean and comparison operators to get a Boolean resultant again.

Let’s consider a few examples and see how to exploit the feature.

The first bracket evaluates True and second to True as well, and the final expression will be True and True, which is True.

We can also use the ‘not’ operator in this kind of expression.

(7 > 3) and (9 != 8) and not False True

In this example, too, the final ‘not False’ evaluates to True, (9 != 8) evaluates to True and (7 > 3) also evaluates to True, which gives us the final expression of (True and True and True) which results to be True.

Note: The expressions inside the brackets are evaluated on priority in Python. The priority of other operators goes like this. If the expression is filled with mathematical operators, the ‘and’ operators, the ‘or’ operators and the ‘not’ operators, then the mathematical operators are evaluated first followed by the ‘not’ operators, followed by the ‘and’ operators and at the end the ‘or’ operators.

Conclusion

Boolean operators are one of the predominant logic that comes in handy while programming, especially while doing some decision making in the logic. Having a thorough knowledge of how they behave would make you an outstanding programmer.

We hope that this EDUCBA information on “Boolean Operators in Python” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Источник

Python If . Else

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

In this example we use two variables, a and b , which are used as part of the if statement to test whether b is greater than a . As a is 33 , and b is 200 , we know that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

Elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".

Example

In this example a is equal to b , so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b , so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif :

Example

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Example

Short Hand If . Else

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Example

One line if else statement:

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example

One line if else statement, with 3 conditions:

And

The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b , AND if c is greater than a :

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b , OR if a is greater than c :

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional statement:

Example

Test if a is NOT greater than b :

Nested If

You can have if statements inside if statements, this is called nested if statements.

Example

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

Источник

Читайте также:  Css media touch screen
Оцените статью