What are Python operators?

An operator in Python is a character that tells the compiler to perform a specific task on the quantity operand.

It can perform the following operations:

  1. Arithmetic
  2. Relational
  3. Logical
svg viewer

Types of operators

  • Unary operators: Requires a single operand. These are mostly prefix.

  • Binary operator: Requires two operands. These are mostly in-fix.

Note: There are also ternary operators.

svg viewer

Types of operations


1. Arithmetic operations

Arithmetic operations are widely used for mathematical calculations. These operators help in solving all types of arithmetic expressions quickly.

operator meaning example
+ It adds two operands together, or acts as a sign for a single operand. 5 + 2 = 7 or +2 (sign)
- It subtracts two operands or acts as a sign for a single operand. 5 - 2 = 3 or -2 (sign)
* It multiplies two operands. 5 * 2 = 10
/ It divides two operands. 10 / 5 = 2
% It returns a remainder after dividing two operands. 5 % 2 = 1

2. Relational (comparison) operations

These operators run a comparison between two entities and return true or false as per the condition.


3. Logical operations

These operators are used for the conditional statements and return a boolean for every expression.

svg viewer
relational operator name example
== Equal 5 == 5
!= Not Equal 6 != 5
> Greater than 6 > 5
< Less than 5 < 6
logical opeartor meaning example
AND It returns true if both of the statements are true. x > 5 and y < 15
OR It returns true if either one of the statements is true. x > 5 and y < 15
NOT It reverses the result, for true it returns false not ( x > 5)

Example

# setting default values for x and y
x = 5
y = 15
print ('x = ', x)
print ('y = ', y)
# arithmetical operation
print ('x + y = ',x + y)
print ('x - y = ',x - y)
print ('x % y = ',x % y)
# relational operation
print ('x > y is ',x > y)
print ('x < y is ',x < y)
print ('x == y is ',x == y)
# logical operation
print ('x > 5 and y < 15 is ',x > 5 and y < 15)
print ('x > 5 or y < 15 is ',x > 5 or y < 15)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved