Python Operators


In Python, operators are symbols that perform operations on variables and values.

Types

Arithmetic

  • handle numeric calculations
  • modulus operator % returns the reminder of the division of two numbers
  • floor division operator // performs division and rounds down to the nearest whole number
    • discards the decimal to provide an integer
OperatorNameExampleResult
+Addition3 + 58
-Subtraction7 - 25
*Multiplication4 * 624
/Division8 / 24.0
%Modulus10 % 31
//Floor Division15 // 43
**Exponentation2 ** 38

Comparison

 A comparison operator is used to compare two values.

OperatorNameExample
==Equalvar1 == var2
!=Not equalvar1 != var2
>Greater thanvar1 > var2
<Less thanvar1 < var2
>=Greater than or equal tovar1 >= var2
Less than or equal tovar1 <= var2

Logical

  • perform logical operations on Boolean values
  • andornot

Assignment

An assignment operator is used to assign a value to a variable.

OperatorExampleEquivalent
=a = 12a = 12
+=a += 7a = a + 7
-=a -= 7a = a - 7
*=a *= 7a = a * 7
/=a /= 7a = a / 7
%=a %= 7a = a % 7
//=a //= 7a = a // 7
**=a **= 7a = a ** 7
&=a &= 7a = a & 7
|=a |= 7a = a | 7
^=a ^= 7a = a ^ 7
>>=a >>= 7a = a >> 7
<<=a << = 7a = a << 7

Membership

Membership operators are used to test whether a value or variable is a member of a sequence or collection.

  • in returns True if a value is found in the sequence
  • not in returns True if a value is not found in the sequence

Identity

 Identity operators are used to compare the memory location of two objects.

  • compare object identities
  • Two kinds:
    • is
      • returns True if both variables point to same object
    • is not
      • Returns True if both variables do not point to the same object

Bitwise

  • manipulate bits in binary representations
  • & (bitwise AND)
  • | (bitwise OR)
  • ^ (bitwise XOR)
  • ~ (bitwise NOT)
  • << (left shift)
  • >> (right shift)

Operate Precedence

  1. Parentheses (): Highest precedence
  2. Exponentiation **: Next highest
  3. Multiplication, Division, Floor Division, Modulus *, /, //, %: Same precedence, evaluated left to right
  4. Addition and Subtraction +-: Same precedence, evaluated left to right
  5. Bitwise Shift <<>>: Lower than arithmetic operations
  6. Bitwise AND &: Lower than shifts
  7. Bitwise XOR ^: Lower than AND
  8. Bitwise OR |: Lowest precedence
  • if same precedence, evaluate left to right