Basics

Python Operators

Python Operators Overview

Python operators include arithmetic and logical, with precedence rules.

Introduction to Python Operators

Operators in Python are special symbols that perform operations on variables and values. Python operators can be classified into several categories, including arithmetic, comparison, logical, assignment, and bitwise operators. Understanding how these operators work is crucial for performing calculations and making logical decisions in your code.

Arithmetic Operators

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

  • Addition (+): Adds two operands.
  • Subtraction (-): Subtracts the second operand from the first.
  • Multiplication (*): Multiplies two operands.
  • Division (/): Divides the first operand by the second.
  • Modulus (%): Returns the remainder of the division.
  • Exponentiation (**): Raises the first operand to the power of the second.
  • Floor Division (//): Divides the first operand by the second and rounds down to the nearest integer.

Comparison Operators

Comparison operators are used to compare two values. These operators return a Boolean value (True or False) based on the comparison.

  • Equal (==): Checks if the values of two operands are equal.
  • Not equal (!=): Checks if the values of two operands are not equal.
  • Greater than (>): Checks if the left operand is greater than the right.
  • Less than (<): Checks if the left operand is less than the right.
  • Greater than or equal to (>=): Checks if the left operand is greater than or equal to the right.
  • Less than or equal to (<=): Checks if the left operand is less than or equal to the right.

Logical Operators

Logical operators are used to combine conditional statements. They include and, or, and not.

  • and: Returns True if both statements are true.
  • or: Returns True if one of the statements is true.
  • not: Reverses the result, returns False if the result is true.

Operator Precedence

Operator precedence determines the order in which operations are performed. In Python, operators with higher precedence are evaluated before operators with lower precedence. Use parentheses to ensure the desired order of operations.

Here is the order of precedence from highest to lowest:

  1. Parentheses ()
  2. Exponentiation **
  3. Multiplication *, Division /, Modulus %, Floor Division //
  4. Addition +, Subtraction -
  5. Comparison ==, !=, <, >, <=, >=
  6. Logical NOT not
  7. Logical AND and
  8. Logical OR or