Python arithmetic operators
Created By: chatGPT
Python provides several arithmetic operators to perform basic mathematical operations. These include addition, subtraction, multiplication, division, modulus, exponentiation, and floor division. Let's explore each operator with examples.
a = 10
b = 3
# Addition
add = a + b # 13
# Subtraction
subtract = a - b # 7
# Multiplication
multiply = a * b # 30
# Division
# Note: Python 3 uses true division
divide = a / b # 3.3333...
# Modulus
modulus = a % b # 1 (the remainder)
# Exponentiation
exponent = a ** b # 1000 (10 to the power of 3)
# Floor Division
floor_divide = a // b # 3 (the quotient without the remainder)
You can use these operators in expressions and they follow the order of operations (parentheses, exponentiation, multiplication and division, addition and subtraction). Here’s how you can use parentheses to change the order of operations:
result = (a + b) * b # (13) * 3 = 39
# Using different operators
complex_expression = a + b * a // b - a % b
# This evaluates to: 10 + (3 * 10 // 3) - (10 % 3) = 10 + 10 - 1 = 19
Here's an illustrative example combining various operators. You can evaluate mathematical expressions using these operators directly in Python:
total = (a + b) * (a - b) / (b + 1)
# This calculates the following: (10 + 3) * (10 - 3) / (3 + 1)
# Result: 39.75
When working with floats or decimal numbers, the division operator will return a floating point result. For instance:
x = 5.0
y = 2.0
float_divide = x / y # 2.5
# However, using floor division on float numbers will return a float too:
floor_float = x // y # 2.0
To demonstrate all these operators in a single program, you can use the following code snippet:
def arithmetic_operations(a, b):
return {
'addition': a + b,
'subtraction': a - b,
'multiplication': a * b,
'division': a / b,
'modulus': a % b,
'exponentiation': a ** b,
'floor_division': a // b
}
results = arithmetic_operations(10, 3)
print(results)