Arithmetic operators
Arithmetic operators in Python are symbols that allow you to perform mathematical calculations such as addition, subtraction, multiplication, and more.
These operators are fundamental for solving problems, from simple calculations to complex logic in your code.
Let’s dive into the basic arithmetic operators and their usage with examples.
Addition +
+
The +
Example:
total = 5 + 3
print(total) # Output: 8
Usage:
Addition is ideal for tasks like summing values, such as a price and its corresponding tax.
Subtraction -
-
The -
Example:
difference = 10 - 4
print(difference) # Output: 6
Usage:
Use subtraction to calculate differences, such as remaining balance or change owed.
Multiplication *
*
The *
Example:
product = 7 * 6
print(product) # Output: 42
Usage:
Multiplication is often used for scaling values, like finding total costs or calculating areas.
Division /
/
The /
Example:
quotient = 20 / 4
print(quotient) # Output: 5.0
Usage:
Division is useful for splitting amounts evenly or finding averages.
Floor division //
//
The //
Example:
floor_div = 20 // 3
print(floor_div) # Output: 6
Usage:
Floor division is ideal for scenarios requiring whole units, such as counting complete groups or full hours.
Modulus %
%
The %
Example:
remainder = 10 % 3
print(remainder) # Output: 1
Usage:
Modulus is useful for tasks like determining whether a number is even or odd, or working with repeating cycles.
Exponentiation **
**
The **
Example:
power = 3 ** 2
print(power) # Output: 9
Usage:
Exponentiation is commonly used for mathematical calculations like squares, cubes, or solving scientific equations.
Combining operators: The order of operations
You can combine arithmetic operators in a single line to perform multiple calculations. Python follows the PEMDAS rule:
- Parentheses
- Exponents
- Multiplication and Division (from left to right)
- Addition and Subtraction (from left to right).
Example:
result = (5 + 3) * 2 - 4 / 2
print(result) # Output: 14.0
Practical applications
1. Calculating Totals
price = 50
tax = 7.5
total_cost = price + (price * tax / 100)
print("Total cost:", total_cost) # Output: Total cost: 53.75
2. Determining even or odd numbers
number = 15
if number % 2 == 0:
print("Even")
else:
print("Odd") # Output: Odd
3. Scaling dimensions
length = 4
width = 5
area = length * width
print("Area:", area) # Output: Area: 20
Conclusion
Arithmetic operators are essential tools in Python, enabling you to perform calculations efficiently. Whether you're adding numbers, finding remainders, or solving equations, these operators make Python a powerful tool for mathematical operations.
Practice using these operators to build confidence and tackle real-world coding challenges!