Arithmetic Operators in Python
TL ; DR:
We can tell computers to perform calculations for us using
+,-,*,/:print(2 + 6) # Prints 8 print(10 - 7) # Prints 3 print(3 * 3) # Prints 9 print(6 / 2) # Prints 3
We can also use variables. In these examples, Python will replace variable
numwith its value6to do the calculations:num = 6 print(num + 5) # Prints 11 print(10 - num) # Prints 4 print(3 * num) # Prints 18 print(num / 2) # Prints 3
Full lesson:
Computers absolutely excel at performing calculations. The "compute" in their name comes from their historical association with providing answers to mathematical questions.
We've learned that in Python there are two types of numbers: integers, which are whole numbers like 10, and floating point numbers or floats, which are numbers with a decimal point like 3.145.
Arithmetic operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
| Operator | Name | Examples |
|---|---|---|
| + | Addition | 3 + 5, x + 5, 3 + y, x + y |
| - | Subtraction | 8 - 3, 8 - y, x - 3, x - y |
| * | Multiplication | 3 * 5, 3 * y, x * 5, x * y |
| / | Division | 8 / 4, 8 / y, x / 8, x / y |
| % | Modulus | 8 % 4, 8 % y, x % 4, x % y |
| ** | Exponentiation | 3 ** 2, 3 ** y, x ** 3, x ** y |
| // | Floor division | 8 // 4, 8 // y, x // 8, x // y |
Note that performing arithmetic on variables does not change the variable - you can only update a variable using the = sign.
Let's go through some examples together to better understand how each operator works:
Addition
# Declare 2 variables and initialize them:
a = 2
b = 3
print(a + b) # Output: 5
print(a + 10) # Output: 12
Subtraction
# Declare 2 variables and initialize them:
a = 2
b = 3
print(a - b) # Output: -1
print(10 - b) # Output: 7
Multiplication
# Declare 2 variables and initialize them:
a = 2
b = 3
print(a * 5) # Output: 10
print(-2 * a * b) # Output: -12
Division
# Declare 2 variables and initialize them:
a = 2
b = 3
print(b / a) # Output: 1.5
print(a / 10) # Output: 0.2
Exponentiation
The ** operator performs the exponential calculation (2**3 translates to 2 * 2 * 2):
# Declare 2 variables and initialize them:
a = 2
b = 3
print(2 ** 3) # Output: 8
print(b ** a) # Output: 9
We left the modulo (%) and floor division (//) operators for the next lesson.
Assignment
Follow the Coding Tutorial and let's practice with arithmetic operators!
Hint
Look at the examples above if you get stuck.
Introduction
In this lesson, we will explore arithmetic operators in Python. Arithmetic operators are fundamental in programming as they allow us to perform basic mathematical operations. These operators are essential for tasks ranging from simple calculations to complex algorithms. Understanding how to use arithmetic operators is crucial for any programmer, as they are used in a wide variety of scenarios, such as data analysis, game development, and financial calculations.
Understanding the Basics
Before diving into the details, let's understand the basic arithmetic operators available in Python:
+(Addition): Adds two numbers.-(Subtraction): Subtracts the second number from the first.*(Multiplication): Multiplies two numbers./(Division): Divides the first number by the second.%(Modulus): Returns the remainder of the division.**(Exponentiation): Raises the first number to the power of the second.//(Floor Division): Divides the first number by the second and returns the largest integer less than or equal to the result.
These operators can be used with both integers and floating-point numbers. Let's look at some simple examples to illustrate these concepts:
print(2 + 3) # Output: 5
print(5 - 2) # Output: 3
print(4 * 3) # Output: 12
print(8 / 2) # Output: 4.0
print(7 % 3) # Output: 1
print(2 ** 3) # Output: 8
print(9 // 2) # Output: 4
Main Concepts
Let's delve deeper into each arithmetic operator and understand how they work with variables:
Addition
a = 2
b = 3
print(a + b) # Output: 5
print(a + 10) # Output: 12
Subtraction
a = 2
b = 3
print(a - b) # Output: -1
print(10 - b) # Output: 7
Multiplication
a = 2
b = 3
print(a * 5) # Output: 10
print(-2 * a * b) # Output: -12
Division
a = 2
b = 3
print(b / a) # Output: 1.5
print(a / 10) # Output: 0.2
Exponentiation
a = 2
b = 3
print(2 ** 3) # Output: 8
print(b ** a) # Output: 9
Examples and Use Cases
Let's explore some real-world use cases where arithmetic operators are beneficial:
Calculating Total Price
price_per_item = 20
quantity = 5
total_price = price_per_item * quantity
print(total_price) # Output: 100
Converting Temperature
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print(fahrenheit) # Output: 77.0
Finding Remainder
total_candies = 29
candies_per_child = 4
remainder = total_candies % candies_per_child
print(remainder) # Output: 1
Common Pitfalls and Best Practices
When working with arithmetic operators, it's important to be aware of common pitfalls and follow best practices:
- Be cautious with division by zero, as it will raise an error.
- Remember that division with
/always returns a float, even if both operands are integers. - Use parentheses to ensure the correct order of operations.
- Keep your code readable by using meaningful variable names.
Advanced Techniques
Once you are comfortable with basic arithmetic operators, you can explore advanced techniques such as:
- Using arithmetic operators in list comprehensions.
- Combining arithmetic operators with functions to create more complex calculations.
- Utilizing the
mathmodule for advanced mathematical operations.
Code Implementation
Here are some well-commented code snippets demonstrating the correct use of arithmetic operators:
# Calculate the area of a rectangle
length = 5
width = 3
area = length * width
print(area) # Output: 15
# Calculate the average of three numbers
num1 = 10
num2 = 20
num3 = 30
average = (num1 + num2 + num3) / 3
print(average) # Output: 20.0
Debugging and Testing
When working with arithmetic operations, debugging and testing are crucial:
- Use print statements to check intermediate results.
- Write test cases to verify the correctness of your functions.
- Use Python's
unittestmodule to automate testing.
import unittest
def add(a, b):
return a + b
class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
Thinking and Problem-Solving Tips
Here are some strategies for approaching problems related to arithmetic operations:
- Break down complex problems into smaller, manageable parts.
- Write pseudocode to outline your approach before coding.
- Practice with coding exercises and projects to improve your skills.
Conclusion
In this lesson, we covered the fundamental arithmetic operators in Python. Mastering these operators is essential for any programmer, as they are used in a wide range of applications. By understanding and practicing these concepts, you will be well-equipped to handle various mathematical operations in your code.
Additional Resources
For further reading and practice, check out the following resources: