After variables and data types, the next important programming concept is understanding operators and expressions.
These are used to perform calculations, compare values, assign data, and create logical conditions.
๐ง 1. What is an Operator?
An operator is a symbol or keyword that tells the computer to perform an operation.
For example:
a = 10
b = 5
result = a + b
Here, "+" is an operator used for addition.
โ 2. Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
Common operators include:
"+" โ Addition
"-" โ Subtraction
"" โ Multiplication
"/" โ Division
"%" โ Remainder
"*" โ Power
Example:
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
These operators are commonly used in calculations and data processing.
๐ 3. Assignment Operators
Assignment operators are used to assign values to variables.
x = 10
x += 5
After this:
x = 15
Common assignment operators:
"="
"+="
"-="
"*="
"/="
They make it easier to update existing values.
๐ 4. Comparison Operators
Comparison operators compare two values and produce a Boolean result such as "True" or "False".
a = 10
b = 5
print(a > b)
print(a == b)
print(a != b)
Common comparison operators:
"==" โ Equal to
"!=" โ Not equal to
">" โ Greater than
"<" โ Less than
">=" โ Greater than or equal to
"<=" โ Less than or equal to
๐ง 5. Logical Operators
Logical operators are used to combine or modify conditions.
The most common ones are:
"and" โ Both conditions must be true
"or" โ At least one condition must be true
"not" โ Reverses the result
Example:
age = 25
has_id = True
print(age >= 18 and has_id)
The result is:
True
๐ค 6. String Operators
Operators can also be used with text.
For example:
first = "Hello"
second = "World"
print(first + " " + second)
Output:
Hello World
The "+" operator joins strings together.
In languages such as Python, "*" can also repeat a string:
print("Hi " * 3)Output:
Hi Hi Hi
๐งฉ 7. What is an Expression?
An expression is a combination of values, variables, and operators that produces a result.
Example:
x = 10
y = 5
result = x * y + 2
The expression:
x * y + 2
produces the value "52".
Expressions are everywhere in programming.
๐ 8. Operator Precedence
When an expression contains multiple operators, programming languages follow rules that determine which operation happens first.
For example:
result = 10 + 5 * 2
Multiplication happens before addition.
So the result is:
20
not "30".
Using parentheses makes the intended order clear:
result = (10 + 5) * 2
Now the result is:
30
๐ 9. Operators Across Languages
The syntax can change slightly between languages, but many fundamental operators are similar.
For example, addition:
Python:
a + b
JavaScript:
a + b
Java:
``
java
a + b``C++:
a + b
โค๏ธ Double Tap & React For More Coding Concepts!