Topic 8 of 58
Arithmetic Operators
Overview
Arithmetic operators perform mathematical calculations. Python includes the standard operators (+, -, , /) but adds highly useful tools tailored for scripting: Floor Division (`//`) which divides and rounds down, Modulo (`%`) which returns the remainder, and Exponentiation (`*`) which raises a number to a power.
Syntax
python
a = 15
b = 4
print(a + b) # 19 (Addition)
print(a - b) # 11 (Subtraction)
print(a * b) # 60 (Multiplication)
# Division (Always returns a float in Python 3)
print(a / b) # 3.75
# Floor Division (Truncates decimal, returns int)
print(a // b) # 3
# Modulo (Remainder of division)
print(a % b) # 3 (Because 15 = 4*3 + 3)
# Exponentiation
print(2 ** 3) # 8 (2 to the power of 3)Common Pitfalls
- Assuming
/between two integers returns an integer (as it does in C++ or Java). In Python 3, true division/always returns a float. - Misunderstanding how modulo
%handles negative numbers. In Python, the result of modulo takes the sign of the divisor, meaning-5 % 3evaluates to1.
Interview Questions
Q:
How can you easily check if a number is even or odd?
A:
By using the modulo operator with 2. If num % 2 == 0, the number is even. If it equals 1, it is odd.
Real-World Example
Converting raw seconds into a readable hours/minutes/seconds format.
example
python
def format_duration(total_seconds):
# Floor division gets whole hours
hours = total_seconds // 3600
# Modulo gets remaining seconds, then floor divides by 60 for minutes
minutes = (total_seconds % 3600) // 60
# Modulo 60 gets the final remaining seconds
seconds = total_seconds % 60
return f"{hours}h {minutes}m {seconds}s"
print(format_duration(3665)) # Output: 1h 1m 5sCheck Your Knowledge
Test your understanding of Arithmetic Operators with these quick questions.