Arithmetic Operations in Python

 

What are Arithmetic Operations? 

Arithmetic operations are the basic math operations you learned in school. Python makes it easy to perform these operations just like a calculator! 

Python supports the following arithmetic operators:

  • + (Addition)
  • - (Subtraction)
  • * (Multiplication)
  • / (Division)
  • // (Floor Division)
  • % (Modulus)
  • ** (Exponentiation)

Let’s break them down one by one! 

Addition (+

Used to add two numbers together.

a = 10
b = 5
sum_result = a + b
print(sum_result)  # Output: 15

You can even add strings!

name = "Python" + " Rocks!"
print(name)  # Output: Python Rocks!

Subtraction (-

Used to find the difference between two numbers.

a = 20
b = 7
difference = a - b
print(difference)  # Output: 13

Multiplication (*

Used to multiply numbers.

a = 6
b = 4
product = a * b
print(product)  # Output: 24

Strings can also be multiplied! (Yes, really!) 

laugh = "Ha" * 3
print(laugh)  # Output: HaHaHa

Division (/

Returns the result of division as a float (decimal number).

a = 10
b = 3
division_result = a / b
print(division_result)  # Output: 3.3333333333333335

Floor Division (//

Divides and rounds down to the nearest whole number.

a = 10
b = 3
floor_div = a // b
print(floor_div)  # Output: 3

Even with floats:

c = 7.5
d = 2
floor_div = c // d
print(floor_div)  # Output: 3.0

Modulus (%

Returns the remainder after division.

a = 10
b = 3
remainder = a % b
print(remainder)  # Output: 1

It’s useful for checking if a number is even or odd:

num = 7
if num % 2 == 0:
    print("Even")
else:
    print("Odd")  # Output: Odd

Exponentiation (**

Raises a number to the power of another number.

base = 2
exponent = 3
result = base ** exponent
print(result)  # Output: 8 (2³ = 8)

Want to calculate square roots? Use ** 0.5

number = 16
sqrt = number ** 0.5
print(sqrt)  # Output: 4.0

Operator Precedence 

Just like in math, Python follows PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction).

result = 10 + 3 * 2  # Multiplication happens first!
print(result)  # Output: 16

Use parentheses to control precedence:

result = (10 + 3) * 2
print(result)  # Output: 26

Summary 

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division (float result)
// Floor Division (integer result)
% Modulus (remainder)
** Exponentiation

Now go forth and do some Python math magic! 

 

Post a Comment

0 Comments