Operators
What Are Operators?
- Operators are used to perform operations on variables and values. For example, using the
+operator to add two numbers:print(10 + 5).
Types of Operators:
Arithmetic Operators:
- Used to perform common mathematical operations.
Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y Assignment Operators:
- Used to assign values to variables.
Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 = x ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 Comparison Operators:
- Used to compare two values.
Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y Logical Operators:
- Used to combine conditional statements.
Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverses the result, returns False if the result is true not(x < 5 and x < 10) Identity Operators:
- Used to compare objects, not if they are equal, but if they are the same object with the same memory location.
Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y Membership Operators:
- Used to test if a sequence is present in an object.
Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y
Operator Precedence:
- Operator precedence determines the order in which operations are performed. Parentheses
()have the highest precedence, followed by exponentiation**, and so on.
Example:
Addition and subtraction have the same precedence, so we evaluate the expression from left to right.
pythonprint(5 + 4 - 7 + 3)- Output:
5
- Output:
Summary:
- Python provides a variety of operators to perform operations on variables and values. Understanding these operators and their precedence is essential for writing effective and efficient code. Practice using these operators to master their usage in Python!