Operators for Performing Operations on Variables and Values
An operator
is a symbol that specifies the operation to be performed between variables or values.
Just as the +
symbol represents addition in mathematics, operators are used in programming to perform various operations between variables or values.
Arithmetic Operators for Mathematical Operations
First, arithmetic operators are used to perform basic mathematical operations between numbers.
-
+
: Addition of numbers, concatenation of strings -
-
: Subtraction, change of sign -
*
: Multiplication, repetition of strings -
/
: Division -
%
: Modulus (remainder) -
**
: Exponentiation -
//
: Floor division
For example, 3 + 5
becomes 8, and 10 / 3
becomes 3.3333...
If you need the integer quotient of 10 divided by 3, then you use 10 // 3
.
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333...
print(a % b) # 1
print(a ** b) # 1000
print(a // b) # 3
The same operator can act differently depending on the data type.
For example, the +
operator can not only add numbers but also concatenate strings.
Similarly, the *
operator can perform both multiplication of numbers and repetition of strings.
name = "World"
greeting = "Hello " + name
print(greeting) # Output: Hello World
print(name * 2) # Output: WorldWorld
Comparison Operators to Determine True/False
Comparison operators compare two values and return True
or False
.
-
==
: Compare if two values are equal -
!=
: Compare if two values are different -
>
: Compare if the left value is greater -
<
: Compare if the right value is greater -
>=
: Compare if the left value is greater or equal -
<=
: Compare if the right value is greater or equal
x = 5
y = 10
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= 5) # True
print(y <= 10) # True
Thus, comparison operators help determine the relationship between variables.
Logical Operators to Combine Conditions
Logical operators are used to combine multiple conditions or to invert the truth value.
In Python, the logical operators are and
, or
, and not
.
-
and
: True only if all conditions are true -
or
: True if at least one condition is true -
not
: Inverts the truth value
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
print(not b) # True
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.