Arithmetic and Logical Operations
Arithmetic and Logical Operations
1. Arithmetic Operators
Operato Exampl
Name Result
r e
+ Addition 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 2 * 3 6
/ Division 10 / 3 3.333
% Modulus 10 % 3 1
** Exponentiation 2 ** 3 8
// Floor Division 10 // 3 3
Key Notes:
Copy
Download
print(10 % 3) # Output: 1
print(-10 % 3) # Output: 2 (math: -10 = (-4)*3 + 2)
2. Assignment Operators
Operato
Example Equivalent To
r
= x = 5 x = 5
+= x += 2 x = x + 2
-= x -= 3 x = x - 3
*= x *= 4 x = x * 4
/= x /= 2 x = x / 2
%= x %= 3 x = x % 3
Example:
x = 10
x **= 2 # x = 10^2 = 100
print(x) # Output: 100
3. Comparison Operators
Operato
Meaning Example Result
r
== Equal to 5 == 5 True
>=
Greater than or equal 10 >= 10 True
to
Use Cases:
Example:
age = 18
is_adult = age >= 18 # is_adult = True
4. Logical Operators
and
Both conditions must be (5 > 3) and (2 < 1) False
true
Short-Circuit Evaluation:
x = 10
if x > 5 and x < 20:
print("Valid range!") # Output: Valid range!
5. Operator Precedence
1. Parentheses ()
2. Exponentiation **
3. Multiplication *, Division /, Floor Division //, Modulus %
4. Addition +, Subtraction -
5. Comparison Operators (==, >, etc.)
6. Logical Operators (not, and, or)
Example:
result = 3 * 3 + 5 - 4 / 4
# Step 1: 3*3 = 9
# Step 2: 4/4 = 1.0
# Step 3: 9 + 5 = 14
# Step 4: 14 - 1.0 = 13.0
print(result) # Output: 13.0
Example:
x = None
if x is None:
print("x has no value!") # Output: x has no value!
7. Type Conversions
Example:
x = 3.14
y = int(x) # y = 3
z = str(y) # z = "3"
Pitfall:
8. Common Mistakes
python
Copy
Download
9. Real-World Applications
1. Input Validation:
user_age = input("Enter your age: ")
if user_age.isdigit() and int(user_age) >= 18:
print("Access granted!")
2. Data Filtering:
numbers = [10, 23, 5, 45, 7]
filtered = [num for num in numbers if num % 2 == 0] # [10]