Operators

background image

Operators are symbols or keywords in programming languages that perform specific operations on one or more operands. Operands are the values or variables on which the operator performs the operation. In general, operators can be classified into several categories such as arithmetic, comparison, logical, and assignment operators.

Arithmetic operators are used to perform mathematical operations such as addition, subtraction, multiplication, and division. For example, in Python:

x = 3
y = 4
result = x + y # result is 7
result = x - y # result is -1
result = x * y # result is 12
result = x / y # result is 0.75

Comparison operators are used to compare two values and return a Boolean value indicating whether the comparison is true or false. For example, in Python:

x = 3
y = 4
result = x > y # result is False
result = x < y # result is True
result = x == y # result is False
result = x != y # result is True

Logical operators are used to combine multiple conditions and return a Boolean value indicating whether the combination is true or false. For example, in Python:

x = 3
y = 4
z = 5
result = x < y and y < z # result is True
result = x < y or y > z # result is True
result = not(x < y) # result is False

Assignment operators are used to assign a value to a variable. The most common assignment operator is the "=" operator, but there are also other operators such as "+=", "-=", "*=", "/=", and so on, that perform the operation and assignment in one step. For example, in Python:

x = 3
y = 4
x += y # x is now 7
x *= 2 # x is now 14

Additionally, there are also bitwise operators, which perform operations on the bits of integers. For example, in Python:

x = 10 # binary: 1010
y = 4 # binary: 0100
result = x & y # binary: 0000, decimal: 0
result = x | y # binary: 1110, decimal: 14
result = x ^ y # binary: 1110, decimal: 14
result = x >> 1 # binary: 0101, decimal: 5
result = x << 1 # binary: 10100, decimal: 20

Lastly, there are also ternary operators, which provide a shorthand way of writing an if-else statement. For example, in Python:

x = 3
y = 4
result = "x is greater" if x > y else "y is greater" # "y is greater"

It is important to note that the use of operators can greatly improve the readability and efficiency of your code. Proper use of operators and understanding when to use certain operators can make a big difference in the overall performance of your program. As a developer, it is important to be familiar with the different types of operators and when to use them, in order to write clear and efficient code.