Python

Operators

YouTube

Operators in Python are special symbols that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.

There are several types of operators in Python:

Arithmetic operators

These include +, -, *, /, %, **, and //. They perform mathematical operations on operands such as addition, subtraction, multiplication, division, and modulus.

 

4 + 1 
# Outputs 5
7 - 4
# Outputs 3
6 * 2
# Outputs 12
16 / 4
# Outputs 4
2 ** 2 
# Outputs 4
5 % 2 
# Outputs 1
6 // 3
# Outputs 2

Comparison operators

These include ==, !=, >, <, >=, and <=. They compare two operands and return a Boolean value of True or False based on whether the comparison is true or false.

 

4 == 4
# Outputs True
3 != 5
# Outputs True
4 > 5
# Outputs False
5 < 2 
# Outputs False
4 >= 4 
# Outputs True
5 <= 6
# Outputs True

Logical operators

These include and, or, and not. They perform logical operations on operands and return a Boolean value based on the truthfulness of the operand.

Assignment operators

These include =, +=, -=, *=, /=, and %=. They assign a value to a variable using different operations. For example:

x = 2 
print(x)
# Outputs 2
x += 1
print(x)
# Outputs 3
x -= 1
print(x)
# Outputs 2
x *= 2
print(x)
# Outputs 4
x /= 1
print(x)
# Outputs 4

Identity operators

These include is and is not. They compare the identity of two operands and return a Boolean value based on whether the operands are the same object or not.

Membership operators

These include in and not in. They test whether an operand is a member of a sequence (such as a list, tuple, or string) and return a Boolean value based on the result of the test.

x = [1, 2, 3, 4, 5]
5 in x
# Outputs True
10 in x 
# Outputs False
10 not in x
# Outputs True
5 not in x 
# Outputs False

The Order of Operations

The order of operations is a set of rules that dictate the order in which arithmetic operations should be performed. In most programming languages, including Python, the order of operations follows the same principles as in mathematics. This means that operations inside parentheses are completed first, followed by exponents and roots, then multiplication and division (performed from left to right), and finally, addition and subtraction (also performed from left to right). It is important to understand and follow the order of operations to ensure that your code produces the correct results.

Using these operators correctly is essential for writing efficient and effective code in Python. They allow you to perform various tasks and make decisions based on the values of operands, which is a key part of programming.