Python Operators
Operators are special symbols used to perform operations on variables and values. Operators help Python perform calculations, comparisons, and logical decisions.
Why Operators are Important?
- Operators perform mathematical calculations.
- Operators compare values.
- Operators help in decision making.
- Operators are heavily used in loops and conditions.
- Operators make coding faster and easier.
Creating Variables
Before using operators, we first create variables.
a = 10 b = 5
Here:
- a stores value 10
- b stores value 5
Addition Operator (+)
The + operator adds two values together.
print(a + b)
Python calculates:
10 + 5
Now Python adds both numbers.
15
So the final answer becomes 15.
Subtraction Operator (-)
The - operator subtracts one value from another.
print(a - b)
Python calculates:
10 - 5
5
So the result becomes 5.
Multiplication Operator (*)
The * operator multiplies numbers.
print(a * b)
Python performs:
10 × 5
50
So the multiplication result becomes 50.
Division Operator (/)
The / operator divides one number by another.
print(a / b)
Python calculates:
10 ÷ 5
2.0
Notice the result is 2.0 instead of 2. Python division always returns decimal output.
Modulus Operator (%)
The modulus operator returns the remainder after division.
print(a % b)
Python checks:
10 ÷ 5
The remainder is:
0
Because 10 divides completely by 5.
Exponent Operator (**)
The ** operator is used for power calculations.
print(a ** b)
Python calculates:
10 × 10 × 10 × 10 × 10
100000
This means 10 raised to the power 5.
Floor Division Operator (//)
Floor division removes decimal values and returns only the whole number.
print(17 // 4)
Actual division:
17 ÷ 4 = 4.25
Floor division removes decimal part.
4
Assignment Operators
Assignment operators are shortcuts used to update variable values.
x = 10
Initially x stores value 10.
Add and Assign (+=)
x += 5
This means:
x = x + 5
Python calculates:
10 + 5 = 15
x = 15
Subtract and Assign (-=)
x -= 2
This means:
x = x - 2
Python calculates:
15 - 2 = 13
x = 13
Multiply and Assign (*=)
x *= 3
This means:
x = x * 3
Python calculates:
13 × 3 = 39
x = 39
Summary
- Operators perform operations on values and variables.
- Arithmetic operators perform mathematical calculations.
- Assignment operators update variable values.
- Division returns decimal output.
- Floor division removes decimal values.
- Modulus returns remainder.
- Exponent operator calculates power.