Python Practice › Basic Programs › Program 10
Formula (a + b)² = a² + b² + 2ab
Write a Python program to solve the formula (a + b)² = a² + b² + 2ab and show both sides are equal.
Input
a = 4, b = 5
Output
(a + b)^2 = 81 a^2 + b^2 + 2ab = 81 Equal: True
Approach
- Calculate the left side and the right side separately.
- Print both and compare them.
Solution
a = 4b = 5 left = (a + b) ** 2right = a ** 2 + b ** 2 + 2 * a * bprint("(a + b)^2 =", left)print("a^2 + b^2 + 2ab =", right)print("Equal:", left == right)Output
(a + b)^2 = 81 a^2 + b^2 + 2ab = 81 Equal: True
Line by line
Line 4
The brackets make Python add before squaring.
Line 5
binds tighter than and +, so a 2 + b * 2 + 2 * a * b follows normal maths order.
Line 8
== returns True, confirming the identity for these values.
Learn the concept
New to this topic? Read the lesson, then come back.