Calculating Numbers with Arithmetic Operators
In Python, you can perform basic arithmetic operations using +
(addition), -
(subtraction), *
(multiplication), and /
(division) operators.
Addition
Use the +
operator. a + b
represents the sum of a and b.
Subtraction
Use the -
operator. a - b
represents the value obtained by subtracting b from a.
Multiplication
Use the *
operator. a * b
represents the product of a and b.
Division
Use the /
operator, which always returns a float. a / b
represents the value obtained by dividing a by b.
Let's look at a simple example to see how each operation works.
Example of Number Operations
a = 10
b = 5
# Addition
print("Addition:", a + b) # Output: 15
# Subtraction
print("Subtraction:", a - b) # Output: 5
# Multiplication
print("Multiplication:", a * b) # Output: 50
# Division
print("Division:", a / b) # Output: 2.0
Operator Precedence
Just like in standard arithmetic, operations inside parentheses are performed first in Python.
Additionally, multiplication and division have higher precedence than addition and subtraction.
Operator Precedence Example
a = 10
b = 5
print("Operator Precedence:", a + b * 2) # Output: 20
print("Operator Precedence:", (a + b) * 2) # Output: 30
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.