Python and or operator precedence

Python Operators

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. In this article, we will look into different types of Python operators.

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication, and division.

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Operator Description Syntax
+ Addition: adds two operands x + y
Subtraction: subtracts two operands x – y
* Multiplication: multiplies two operands x * y
/ Division (float): divides the first operand by the second x / y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by the second x % y
** Power: Returns first raised to power second x ** y
Читайте также:  Есть ли visual java

Example of Arithmetic Operators in Python

Division Operators

Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient.

There are two types of division operators:

Float division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Python3

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Python3

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in python is as follows:

  1. P – Parentheses
  2. E – Exponentiation
  3. M – Multiplication (Multiplication and division have the same precedence)
  4. D – Division
  5. A – Addition (Addition and subtraction have the same precedence)
  6. S – Subtraction

The modulus operator helps us extract the last digit/s of a number. For example:

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Python3

Note: Refer to Differences between / and // for some interesting facts about these two operators.

Comparison Operators in Python

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

Operator Description Syntax
> Greater than: True if the left operand is greater than the right x > y
Less than: True if the left operand is less than the right x < y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than or equal to the right x >= y
Less than or equal to True if the left operand is less than or equal to the right x

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Python3

False True False True False True

Logical Operators in Python

Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements.

Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x

Precedence of Logical Operators in Python

The precedence of Logical Operators in python is as follows:

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Python3

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Operator Description Syntax
& Bitwise AND x & y
| Bitwise OR x | y
~ Bitwise NOT ~x
^ Bitwise XOR x ^ y
>> Bitwise right shift x>>
Bitwise left shift x

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in python is as follows:

  1. Bitwise NOT
  2. Bitwise Shift
  3. Bitwise AND
  4. Bitwise XOR
  5. Bitwise OR

Bitwise Operators in Python

Here is an example showing how Bitwise Operators in Python work:

Python3

Assignment Operators in Python

Python Assignment operators are used to assign values to the variables.

Operator Description Syntax
= Assign the value of the right side of the expression to the left side operand x = y + z
+= Add AND: Add right-side operand with left-side operand and then assign to left operand a+=b a=a+b
-= Subtract AND: Subtract right operand from left operand and then assign to left operand a-=b a=a-b
*= Multiply AND: Multiply right operand with left operand and then assign to left operand a*=b a=a*b
/= Divide AND: Divide left operand with right operand and then assign to left operand a/=b a=a/b
%= Modulus AND: Takes modulus using left and right operands and assign the result to left operand a%=b a=a%b
//= Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand a//=b a=a//b
**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand a**=b a=a**b
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b
Performs Bitwise left shift on operands and assign value to left operand a

Assignment Operators in Python

Let’s see an example of Assignment Operators in Python.

Источник

Precedence and Associativity of Operators in Python

The combination of values, variables, operators, and function calls is termed as an expression. The Python interpreter can evaluate a valid expression.

Here 5 — 7 is an expression. There can be more than one operator in an expression.

To evaluate these types of expressions there is a rule of precedence in Python. It guides the order in which these operations are carried out.

For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence # than subtraction >>> 10 - 4 * 2 2

But we can change this order using parentheses () as it has higher precedence than multiplication.

# Parentheses () has higher precedence >>> (10 - 4) * 2 12

The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence than the lower ones).

Operators Meaning
() Parentheses
** Exponent
+x , -x , ~x Unary plus, Unary minus, Bitwise NOT
* , / , // , % Multiplication, Division, Floor division, Modulus
+ , — Addition, Subtraction
> Bitwise shift operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
== , != , > , >= , < , Comparisons, Identity, Membership operators
not Logical NOT
and Logical AND
or Logical OR

Let’s look at some examples:

Suppose we’re constructing an if. else block which runs if when lunch is either fruit or sandwich and only if money is more than or equal to 2 .

# Precedence of or & and meal = "fruit" money = 0 if meal == "fruit" or meal == "sandwich" and money >= 2: print("Lunch being delivered") else: print("Can't deliver lunch")

This program runs if block even when money is 0 . It does not give us the desired output since the precedence of and is higher than or .

We can get the desired output by using parenthesis () in the following way:

# Precedence of or & and meal = "fruit" money = 0 if (meal == "fruit" or meal == "sandwich") and money >= 2: print("Lunch being delivered") else: print("Can't deliver lunch")

Associativity of Python Operators

We can see in the above table that more than one operator exists in the same group. These operators have the same precedence.

When two operators have the same precedence, associativity helps to determine the order of operations.

Associativity is the order in which an expression is evaluated that has multiple operators of the same precedence. Almost all the operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluated first.

# Left-right associativity # Output: 3 print(5 * 2 // 3) # Shows left-right associativity # Output: 0 print(5 * (2 // 3))

Note: Exponent operator ** has right-to-left associativity in Python.

# Shows the right-left associativity of ** # Output: 512, Since 2**(3**2) = 2**9 print(2 ** 3 ** 2) # If 2 needs to be exponated fisrt, need to use () # Output: 64 print((2 ** 3) ** 2)

We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2) .

Non associative operators

Some operators like assignment operators and comparison operators do not have associativity in Python. There are separate rules for sequences of this kind of operator and cannot be expressed as associativity.

Furthermore, while chaining of assignments like x = y = z = 1 is perfectly valid, x = y = z+= 2 will result in error.

# Initialize x, y, z x = y = z = 1 # Expression is invalid # (Non-associative operators) # SyntaxError: invalid syntax x = y = z+= 2
 File "", line 8 x = y = z+= 2 ^ SyntaxError: invalid syntax

Table of Contents

Источник

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