Python

Simple Python Guide For Beginners

22 min read

Python Operators

In Python, operators are symbols used to perform operations on operands. Python supports various types of operators, including arithmetic operators, assignment operators, comparison operators, logical operators, identity operators, and membership operators. Let’s explore each of these operator categories.

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations on numeric operands. Python supports common arithmetic operators such as addition, subtraction, multiplication, division, modulo, and exponentiation.

x = 10
y = 3
addition = x + y
subtraction = x - y
multiplication = x * y
division = x / y
modulo = x % y
exponentiation = x ** y
Assignment Operators

Assignment operators are used to assign values to variables. They provide a concise way to update variable values based on calculations or other operations.

x = 10
y = 3
x += y  # Equivalent to x = x + y
x -= y  # Equivalent to x = x - y
x *= y  # Equivalent to x = x * y
x /= y  # Equivalent to x = x / y
x %= y  # Equivalent to x = x % y
x **= y  # Equivalent to x = x ** y
Comparison Operators

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

x = 10
y = 3
greater_than = x > y
less_than = x < y
greater_than_or_equal = x >= y
less_than_or_equal = x <= y
equal = x == y
not_equal = x != y
Logical Operators

Logical operators are used to combine multiple conditions and evaluate the result based on their logical relationship.

x = 10
y = 3
logical_and = x > 5 and y < 10
logical_or = x > 5 or y < 10
logical_not = not (x > 5)
Identity Operators

Identity operators are used to check if two variables refer to the same object in memory.

x = [1, 2, 3]
y = [1, 2, 3]
z = x
identity_check = x is y
identity_check_negation = x is not y
identity_check_same = x is z
Membership Operators

Membership operators are used to check if a value is present in a sequence (such as a string, list, or tuple).

x = [1, 2, 3]
membership_check = 2 in x
membership_check_negation = 4 not in x

Content List