Python Operators - Simple Guide for Beginners
1. Arithmetic Operators
These operators are used to do simple math like addition or subtraction.
Examples:
- 2 + 3 = 5 (Add)
- 5 - 1 = 4 (Subtract)
- 3 * 2 = 6 (Multiply)
- 6 / 2 = 3.0 (Divide)
- 2 ** 3 = 8 (Power: 2 raised to 3)
- 7 % 3 = 1 (Remainder after dividing 7 by 3)
2. Comparison Operators
Used to compare two values. It returns True or False.
Examples:
- 5 == 5 True (Is equal?)
- 3 != 4 True (Not equal?)
- 5 > 2 True (Greater than?)
- 2 < 5 True (Less than?)
- 3 >= 3 True (Greater or equal?)
- 4 <= 5 True (Less or equal?)
3. Logical Operators
Used to combine conditions.
Examples:
- 5 > 3 and 2 < 4 True (Both are true)
- 5 > 3 or 2 > 10 True (One is true)
- not (5 > 3) False (Opposite of True)
Python Operators - Simple Guide for Beginners
4. Assignment Operators
Used to give or change the value of a variable.
Examples:
- x = 10 (Give value 10 to x)
- x += 5 (Add 5 to x)
- x -= 3 (Subtract 3 from x)
- x *= 2 (Multiply x by 2)
- x /= 2 (Divide x by 2)
5. Membership Operators
Used to check if a value is inside a list or not.
Examples:
- 'a' in ['a', 'b'] True (Is 'a' in the list? Yes)
- 'x' not in ['a', 'b'] True (Is 'x' not in the list? Yes)
6. Identity Operators
Used to check if two variables refer to the exact same object.
Examples:
x = [1, 2, 3]
y = [1, 2, 3]
- x == y True (They look the same)
- x is y False (They are not the same object)
z=x
- x is z True (They are the same object)