Operators and Expressions
Operators and expressions are fundamental components of Python that allow you to perform various computations and manipulations on data. In this tutorial, we will explore different types of operators and how they are used to create expressions in Python.
Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
| Operator | Description | Example | Result |
|---|---|---|---|
+ |
Addition | 5 + 3 |
8 |
- |
Subtraction | 10 - 2 |
8 |
* |
Multiplication | 4 * 5 |
20 |
/ |
Division | 10 / 2 |
5.0 |
% |
Modulo (Remainder) | 10 % 3 |
1 |
** |
Exponentiation | 2 ** 3 |
8 |
// |
Floor Division | 10 // 3 |
3 |
Assignment Operators
Assignment operators are used to assign values to variables.
x = 10 # Assign the value 10 to variable x
y += 5 # Equivalent to: y = y + 5
Comparison Operators
Comparison operators are used to compare values and return boolean results (True or False).
x == y # Equal to
x != y # Not equal to
x > y # Greater than
x < y # Less than
x >= y # Greater than or equal to
x <= y # Less than or equal to
Logical Operators
Logical operators are used to combine multiple conditions and evaluate the overall expression.
x and y # True if both x and y are True
x or y # True if either x or y is True
not x # True if x is False (negation)
Bitwise Operators
Bitwise operators perform operations on individual bits of integers.
x & y # Bitwise AND
x | y # Bitwise OR
x ^ y # Bitwise XOR
~x # Bitwise NOT (complement)
x << y # Bitwise left shift
x >> y # Bitwise right shift
Identity Operators
Identity operators are used to compare the memory locations of two objects.
x is y # True if x and y reference the same object
x is not y # True if x and y reference different objects
Membership Operators
Membership operators are used to check if a value exists in a sequence (e.g., list, tuple, string).
x in sequence # True if x is present in the sequence
x not in sequence # True if x is not present in the sequence
Expressions
Expressions are combinations of variables, values, and operators that are evaluated to produce a result.
x = 5
y = 10
result = x + y # Expression: x + y