Introduction to Python Operators
Python Operators
Operators are symbols or special characters that perform operations on operands (values or variables).
Python provides a wide range of operators that can be used for various purposes, such as mathematical calculations, logical comparisons, assignment, membership testing, and more.
Here are some of the commonly used operators in Python:
Arithmetic Operators
+
: Addition-
: Subtraction*
: Multiplication/
: Division (returns a float)//
: Floor Division (returns an integer)%
: Modulo (returns the remainder of division)**
: Exponentiation (raises a number to a power)
x = 10
y = 3
print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.3333333333333335
print(x // y) # Output: 3
print(x % y) # Output: 1
print(x ** y) # Output: 1000
Assignment Operators
=
: Assigns a value to a variable+=
: Adds the right operand to the left operand and assigns the result to the left operand-=
: Subtracts the right operand from the left operand and assigns the result to the left operand*=
: Multiplies the right operand with the left operand and assigns the result to the left operand/=
: Divides the left operand by the right operand and assigns the result to the left operand//=
: Performs floor division on the left operand by the right operand and assigns the result to the left operand%=
: Calculates the modulus of the left operand with the right operand and assigns the result to the left operand**=
: Performs exponentiation on the left operand with the right operand and assigns the result to the left operand
x = 10
y = 3
x += y # Equivalent to x = x + y
print(x) # Output: 13
x -= y # Equivalent to x = x - y
print(x) # Output: 10
x *= y # Equivalent to x = x * y
print(x) # Output: 30
x /= y # Equivalent to x = x / y
print(x) # Output: 10.0
x //= y # Equivalent to x = x // y
print(x) # Output: 3.0
x %= y # Equivalent to x = x % y
print(x) # Output: 0.0
x **= y # Equivalent to x = x ** y
print(x) # Output: 0.0
Comparison Operators
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
x = 5
y = 10
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: False
print(x < y) # Output: True
print(x >= y) # Output: False
print(x <= y) # Output: True
Logical Operators
and
: ReturnsTrue
if both operands areTrue
or
: ReturnsTrue
if at least one of the operands isTrue
not
: Returns the opposite Boolean value of the operand
x = 5
y = 10
z = 7
print(x < y and z > x) # Output: True
print(x > y or z > x) # Output: True
print(not (x > y)) # Output: True
Membership Operators
in
: Returns True if a value is found in a sequencenot in
: Returns True if a value is not found in a sequence
fruits = ["apple", "banana", "orange"]
print("apple" in fruits) # Output: True
print("kiwi" not in fruits) # Output: True