Welcome back, budding Pythonistas! Now that you know how to store information using variables, let's explore how to manipulate that data using Python's arithmetic operators. These are the building blocks for performing calculations, just like you'd use in a math class, but now with the power to automate complex computations.
Python provides a familiar set of operators for performing basic arithmetic. Let's break them down:
- Addition (
+): This operator adds two operands (numbers or variables) together.
num1 = 10
num2 = 5
sum_result = num1 + num2
print(f"The sum is: {sum_result}")- Subtraction (
-): This operator subtracts the second operand from the first.
num1 = 10
num2 = 5
difference_result = num1 - num2
print(f"The difference is: {difference_result}")- Multiplication (
*): This operator multiplies two operands.
num1 = 10
num2 = 5
product_result = num1 * num2
print(f"The product is: {product_result}")- Division (
/): This operator divides the first operand by the second. In Python 3, this always results in a floating-point number (a number with a decimal).
num1 = 10
num2 = 5
division_result = num1 / num2
print(f"The division result is: {division_result}")- Floor Division (
//): This operator performs division but discards any fractional part, returning only the whole number (integer) result. It effectively rounds down to the nearest whole number.
num1 = 10
num2 = 3
floor_division_result = num1 // num2
print(f"The floor division result is: {floor_division_result}")
num3 = 11
num4 = 3
floor_division_result_2 = num3 // num4
print(f"Another floor division example: {floor_division_result_2}")- Modulo (
%): This operator returns the remainder of a division. It's incredibly useful for tasks like determining if a number is even or odd, or for cycling through a sequence of values.
num1 = 10
num2 = 3
modulo_result = num1 % num2
print(f"The remainder is: {modulo_result}")
# Checking for even numbers:
number_to_check = 7
if number_to_check % 2 == 0:
print(f"{number_to_check} is even")
else:
print(f"{number_to_check} is odd")- Exponentiation (
**): This operator raises the first operand to the power of the second operand. Think of it as repeated multiplication.
base = 2
exponent = 3
exponent_result = base ** exponent
print(f"{base} raised to the power of {exponent} is: {exponent_result}")Understanding these arithmetic operators is fundamental to writing any program that performs calculations. You'll use them constantly to process data, perform simulations, and build complex logic. Experiment with them in your Python interpreter and see the results!