Welcome to the world of arithmetic operators in Python! These essential tools help you perform mathematical operations, making your programs more dynamic and powerful. By the end of this lesson, you'll have a solid understanding of how to add, subtract, multiply, divide, and even raise numbers to powers using arithmetic operators.
In Python, we use five basic arithmetic operators: +
, -
, *
, /
, and **
. Let's delve into each one with examples:
+
): Combines two numbers to produce a new value.python
result = 5 + 3 # This will output: 8
-
): Removes one number from another.python
difference = 10 - 4 # This will output: 6
*
): Multiplies two numbers together.python
product = 2 * 5 # This will output: 10
/
): Divides one number by another.python
quotient = 9 / 3 # This will output: 3.0
**
): Raises a base to an exponent.python
square = 2 ** 2 # This will output: 4
Let's take a look at some real-world examples of using arithmetic operators in Python:
5
and height 7
:python
area = 5 * 7 # This will output: 35 (the area of the rectangle)
python
total_seconds = 4 * 60 + 30 # This will output: 258 (4 minutes equals 240 seconds, adding 30 more)
What causes it: Attempting to use a variable that has not been defined yet.
# Bad code example that triggers the NameError
print(undeclared_variable * 2)
Error message:
NameError: name 'undeclared_variable' is not defined
Solution: Make sure all variables are declared before using them in your code.
# Corrected code
undeclared_variable = 5
print(undeclared_variable * 2)
Why it happens: Python doesn't automatically create variables, so you must explicitly declare them first.
How to prevent it: Declare all your variables before using them in your code.
What causes it: Trying to perform an arithmetic operation on objects of incompatible types (e.g., string and number).
# Bad code example that triggers the TypeError
print("5" + 3)
Error message:
TypeError: can't convert 'int' object to str implicitly
Solution: Make sure both operands are of the same data type or convert one to match before performing an arithmetic operation.
# Corrected code
print(str(5) + str(3)) # This will output: '53' (string concatenation, not arithmetic addition)
Why it happens: Python requires both operands to be of the same data type for most arithmetic operations.
How to prevent it: Ensure that your operands are compatible types before performing an arithmetic operation.
()
to clarify complex expressions and make them easier to read.decimal
for high-precision calculations, as the built-in float type may have limited precision.+
), subtraction (-
), multiplication (*
), division (/
), and exponentiation (**
).NameError
and TypeError
, and learn how to avoid them in your code.