Python Operators


 

In Python, operators are symbols or tokens that perform a specific operation on one or more operands. Operators can be used to perform a wide range of tasks, from basic arithmetic to assignment and comparison.

Here are some examples of common operators in Python:

Arithmetic Operators

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

# addition x = 2 + 3 # subtraction x = 5 - 2 # multiplication x = 4 * 6 # division x = 10 / 2 # remainder (modulus) x = 11 % 3 # exponentiation x = 2 ** 3

Comparison Operators

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

# equal to x = 2 == 2 # not equal to x = 2 != 3 # greater than x = 4 > 3 # less than x = 2 < 5 # greater than or equal to x = 2 >= 2 # less than or equal to x = 4 <= 5

Assignment Operators

Assignment operators are used to assign a value to a variable.

# basic assignment x = 5 # compound assignment x += 2 # equivalent to x = x + 2 x -= 3 # equivalent to x = x - 3 x *= 4 # equivalent to x = x * 4 x /= 5 # equivalent to x = x / 5 x %= 6 # equivalent to x = x % 6 x **= 7 # equivalent to x = x ** 7

Logical Operators

Logical operators are used to perform logical operations like AND, OR, and NOT.

# AND x = True and False # OR x = True or False # NOT x = not True

Identity Operators

Identity operators are used to compare the identity of two objects.

# is x = [1, 2, 3] y = [1, 2, 3] z = x print(x is y) # False print(x is z) # True # is not print(x is not y) # True print(x is not z) # False

Membership Operators

Membership operators are used to test if an element is a member of a sequence (like a list or a string).

# in x = 'cat' y = 'dog' z = ['cat', 'dog'] print('cat' in x) # True print('cat' in y) # False print('cat' in z) # True # not in print('cat' not in x) # False print('cat' not in y) # True print('cat' not in z) # False

Overall, operators are a crucial part of Python programming, allowing you to perform a wide range of tasks and operations on data. Whether you're working with basic arithmetic, comparison, assignment, logical, identity, or membership operators, they provide a powerful and flexible way to manipulate and work with data in your code.


No comments

Powered by Blogger.