Simple Arithmetic

➕➖ Simple Arithmetic in Python

Python provides basic arithmetic operators to perform calculations with numbers. These can be used with integers, floats, and even NumPy arrays for vectorized arithmetic.


✅ 1. Basic Arithmetic Operators

Operator Description Example
+ Addition 5 + 3 = 8
- Subtraction 5 - 3 = 2
* Multiplication 5 * 3 = 15
/ Division (float) 5 / 2 = 2.5
// Floor Division 5 // 2 = 2
% Modulus (remainder) 5 % 2 = 1
** Exponentiation 5 ** 2 = 25

✅ 2. Examples with Numbers

a = 10
b = 3

print("Addition:", a + b) # 13
print("Subtraction:", a - b) # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.3333
print("Floor Division:", a // b) # 3
print("Modulus:", a % b) # 1
print("Exponent:", a ** b) # 1000


✅ 3. Using Arithmetic with Floats

x = 5.5
y = 2.0

print(x + y) # 7.5
print(x / y) # 2.75
print(x * y) # 11.0

  • Division / always returns float

  • Floor division // truncates to integer


✅ 4. Arithmetic with NumPy Arrays

NumPy allows element-wise arithmetic on arrays:

import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

print("Addition:", arr1 + arr2) # [5 7 9]
print("Subtraction:", arr1 - arr2) # [-3 -3 -3]
print("Multiplication:", arr1 * arr2) # [4 10 18]
print("Division:", arr2 / arr1) # [4. 2.5 2.]
print("Exponent:", arr1 ** 2) # [1 4 9]

  • Operations are vectorized → very fast


✅ 5. Using Parentheses for Precedence

result = (2 + 3) * 4 # 20
result2 = 2 + 3 * 4 # 14 (multiplication before addition)
  • Use parentheses () to control order of operations


🎯 Practice Exercises

  1. Compute (15 + 5) * 2 - 8 / 4 using Python arithmetic operators.

  2. Create two NumPy arrays [1,2,3] and [4,5,6] and compute their sum, difference, and product.

  3. Compute square, cube, and modulus of numbers from 1 to 5 using Python or NumPy.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *