Python Practice › Basic Programs › Program 10

Formula (a + b)² = a² + b² + 2ab

EasyBasic Programs · 10 of 40

Write a Python program to solve the formula (a + b)² = a² + b² + 2ab and show both sides are equal.

Advertisement
Input
a = 4, b = 5
Output
(a + b)^2 = 81
a^2 + b^2 + 2ab = 81
Equal: True

Approach

  1. Calculate the left side and the right side separately.
  2. Print both and compare them.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs