Table of Contents
To calculate the area of a square in Python, multiply the side length by itself: area = side * side. If the side is 3.2 cm, the area is 10.24 cm². You only need one side length because all four sides are equal.

Read the side length and print the area
import math
try:
side = float(input("Enter the side length: "))
except ValueError:
print("Enter a number, such as 3.2.")
else:
if not math.isfinite(side) or side <= 0:
print("Enter a positive, finite side length.")
else:
area = side * side
print(f"Area: {area:.4f} square units")
For an input of 3.2, the program prints Area: 10.2400 square units. The :.4f format displays four decimal places. Use meters squared, centimeters squared or another unit that matches the input.
Use exponentiation in a reusable function
def square_area(side):
return side ** 2
print(f"{square_area(2.4):.4f}") # 5.7600
pow(side, 2) performs the same calculation. Use one expression consistently. If the function will receive unchecked user input, validate the side before calling it or include validation in the function. TipsMake’s Python Fundamentals course covers numbers, functions and handling invalid input.
Reader Comments 0
Sign in with email or Google to join the discussion.