Arithmetic in Python

Arithmetic in Python with Examples and Assignments

Arithmetic in Python — From Basics to Complex Numbers

Learn operators, precedence, parentheses, complex numbers, and practical examples. Try assignments and reveal answers interactively.

1) Complex Numbers in Python

z1 = 3 + 4j
z2 = 1 - 2j

print(z1 + z2)   # (4+2j)
print(z1 * z2)   # (11-2j)
print(abs(z1))   # 5.0

2) Parentheses and Precedence

result1 = 10 + 5 * 2 ** 2
print(result1)   # 30

result2 = (10 + 5) * (2 ** 2)
print(result2)   # 60

3) Square Roots: Two Variations

Python allows you to compute square roots either with math.sqrt() or by raising a number to the power of 0.5.

import math

print(math.sqrt(16))   # 4.0 (using math.sqrt)

print(16 ** 0.5)       # 4.0 (using exponentiation)

You can extend this idea for other roots:

print(27 ** (1/3))   # 3.0 (cube root)
print(32 ** 0.2)     # 2.0 (5th root)

4) Practical Examples

a) Area of Triangle

a, b, c = 5, 6, 7
s = (a + b + c) / 2
area1 = (s*(s-a)*(s-b)*(s-c)) ** 0.5   # using **0.5
area2 = math.sqrt(s*(s-a)*(s-b)*(s-c)) # using math.sqrt
print(area1, area2)

b) Quadratic Equations

import cmath
a, b, c = 1, 2, 5
d = (b**2) - (4*a*c)

r1 = (-b + cmath.sqrt(d)) / (2*a)
r2 = (-b - cmath.sqrt(d)) / (2*a)
print(r1, r2)

5) Assignments (Click to Show Answer)

Q1: Calculate perimeter and area of a rectangle (length=12, breadth=8).

length, breadth = 12, 8
perimeter = 2*(length + breadth)
area = length * breadth
print(perimeter, area)  # 40, 96

Q2: Solve quadratic equation x² + 3x + 2 = 0.

import cmath
a, b, c = 1, 3, 2
d = (b**2) - (4*a*c)
r1 = (-b + cmath.sqrt(d))/(2*a)
r2 = (-b - cmath.sqrt(d))/(2*a)
print(r1, r2)  # (-1+0j), (-2+0j)

Q3: Find the Simple Interest for P=2000, R=7%, T=3 years.

P, R, T = 2000, 7, 3
SI = (P * R * T)/100
print(SI)  # 420

Q4 (Multi-Step): Given the area of a circle (314), find the radius, then use it to compute the circumference and diameter. Try both **0.5 and math.sqrt() for the square root.

import math
area = 314
# radius with **0.5
radius1 = (area / math.pi) ** 0.5
# radius with math.sqrt
radius2 = math.sqrt(area / math.pi)

circumference = 2 * math.pi * radius1
diameter = 2 * radius1
print(radius1, radius2, circumference, diameter)
# ~10.0, ~10.0, ~62.83, ~20.0

Q5 (Multi-Step): A savings account earns compound interest at 8% per year. If you invest 2000 for 3 years, first compute the total amount, then subtract principal to find interest.

P, R, T = 2000, 8, 3
A = P * ((1+R/100)**T)
CI = A - P
print(A, CI)  
# 2519.42, 519.42

Q6 (Multi-Step): Given speed=60 km/h and time=2.5 h, calculate distance. Then convert distance to meters.

speed, time = 60, 2.5
distance_km = speed * time
distance_m = distance_km * 1000
print(distance_km, distance_m)  # 150.0, 150000.0

© Champak Roy • Python Arithmetic with Complex Numbers and Multi-Step Assignments

Post a Comment

0 Comments

Me