Resources | Subject Notes | Computer Science
This section explores the fundamental operators used in programming to perform calculations, make comparisons, and create conditional statements. Understanding these operators is crucial for writing effective and complex programs.
Arithmetic operators are used to perform mathematical calculations. The most common arithmetic operators are:
+
- Adds two values together.-
- Subtracts one value from another.*
- Multiplies two values./
- Divides one value by another. This always results in a floating-point number.%
- Returns the remainder of a division.**
- Raises a value to a power. For example, 2**3
is 2 raised to the power of 3 (which is 8).Example:
In Python:
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: 1
print(x ** y) # Output: 1000
Logical operators are used to combine boolean expressions (which evaluate to either True
or False
). The main logical operators are:
Operator | Description | Example | Result |
---|---|---|---|
and |
Returns True if both operands are True . Otherwise, returns False . |
(x > 5) and (y < 10) |
True (if x > 5 and y < 10) |
or |
Returns True if at least one operand is True . Returns False only if both operands are False . |
(x > 5) or (y < 10) |
True (if x > 5 or y < 10) |
not |
Reverses the boolean value of its operand. If the operand is True , it returns False , and vice versa. |
not (x > 5) |
False (if x > 5 is False) |
Boolean operators are used to evaluate conditions that result in True
or False
. They are often used in conjunction with comparison operators.
Common comparison operators include:
==
- Equal to!=
- Not equal to>
- Greater than<
- Less than>=
- Greater than or equal to<=
- Less than or equal toExample:
In Python:
x = 10
y = 3
print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False
Combining Operators:
You can combine arithmetic, logical, and boolean operators to create complex expressions. It's important to use parentheses ()
to control the order of operations, just like in mathematics.
Example:
age = 20
has_license = True
if age >= 18 and has_license:
print("Eligible to drive")
else:
print("Not eligible to drive")