🟢 Beginner · Lesson 07
Operators in Python
What are Operators?
Operators are symbols that perform operations on values (called operands). 5 + 3 uses the + operator on operands 5 and 3.
Arithmetic Operators
| Op | Meaning | Example | Result |
|---|---|---|---|
| + | Add | 5 + 2 | 7 |
| - | Subtract | 5 - 2 | 3 |
| * | Multiply | 5 * 2 | 10 |
| / | Divide (float) | 5 / 2 | 2.5 |
| // | Floor divide | 5 // 2 | 2 |
| % | Modulus (remainder) | 5 % 2 | 1 |
| ** | Power | 5 ** 2 | 25 |
Comparison Operators
Return True or False: == (equal), != (not equal), >, <, >=, <=.
Logical Operators
and (both true), or (at least one true), not (reverse).
Assignment Operators
= assigns. Shortcuts: +=, -=, *=, /=. So x += 5 means x = x + 5.
Program 1: Arithmetic
Python – arithmetic.py
a = 17
b = 5
print("Sum :", a + b)
print("Quotient :", a // b)
print("Remainder:", a % b)
print("Power :", a ** 2)Sum : 22
Quotient : 3
Remainder: 2
Power : 289
//gives the whole-number part of division (3, not 3.4).%gives the remainder (17 = 5*3 + 2).**is power: 17 squared = 289.
Program 2: Comparison & Logical
Python – logic.py
age = 20 has_id = True print(age >= 18) # comparison print(age >= 18 and has_id) # both must be true print(age < 13 or has_id) # one true is enough print(not has_id) # reverse
True
True
True
False
andneeds both sides true.oris true if any side is true.notflips True to False.
Program 3: Even/Odd & Leap Year
Python – checks.py
num = int(input("Enter a number: "))
# Even/Odd using modulus
if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")
# Leap year check using logical operators
year = int(input("Enter a year: "))
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(year, "leap year?", is_leap)Enter a number: 7
7 is Odd
Enter a year: 2024
2024 leap year? True
num % 2 == 0is the classic even-number test.- The leap-year rule combines
and,orand!=in one expression.
Operator Precedence
Python follows BODMAS-like rules: ** first, then * / // %, then + -, then comparisons, then not, and, or. Use brackets to be safe: (a + b) * c.
Common Mistakes
- Using
=(assign) instead of==(compare) in conditions. - Expecting
/to give a whole number — use//for that. - Writing
&&/||(C style) instead ofand/or.
Practice Tasks
- Take two numbers and print all 7 arithmetic results.
- Check if a number is divisible by both 3 and 5 using
and. - Ask age and check eligibility to vote (>= 18).
- Swap two numbers using
+=style operators.
Summary
- Arithmetic:
+ - * / // % **. - Comparison returns bool; logical:
and or not. %for even/odd,//for whole-number division.- Use brackets to control precedence.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.