How to calculate the area of ​​a square in Python

A square is a two-dimensional closed figure with four equal sides. Each angle of a square measures 90 degrees. The area of ​​a square is the space enclosed within its four sides. In this problem, we are given one side of a square and have to find the area of ​​that square .

How to calculate the area of ​​a square in Python Picture 1

The tutorial below helps you find the area of ​​a given square in Python using different methods .

Using the multiplication operator (*)

Below is a simple program to calculate area using the multiplication operator (*). The input is taken as a float and the area is calculated to 4 decimal places. We will use the " %.4f " specifier to get 4 digits after the decimal point. In " %.4f ", the number after the decimal point is used to indicate the decimal places and f specifies float .

Algorithm

  1. Step 1- Get input of square side from user
  2. Step 2 - Calculate the area
  3. Step 3- Print the area using " %.4f "

Python Programming

#diện tích hình vuông s=float(input("Enter side of square")) area=s*s print("Area of square=",'%.4f'%area)

Result

Enter side of square3.2 Area of square= 10.2400

Using the pow() function

pow() is a predefined mathematical function in Python that returns the value x to the power of y .

Algorithm

  1. Step 1- Define area_square() function to calculate area. Get edge input from user
  2. Step 2 - Call pow() and set the parameter as n,2 to calculate the area
  3. Step 3- Get input data from user
  4. Step 4- Call area_square() and pass the input data as parameter
  5. Step 5- Print area

Python Program

def area_square(n): area = pow(n,2) return area num=float(input("Enter number") ) print("Sum of digits",area_square(num))

Result

Enter side of square2.4 Area of square= 5.7600

In this tutorial, we learned how to calculate the area of ​​a square using two approaches. One is to use simple statements to multiply and print the result. The other is to use a predefined mathematical function called pow() . You can also define a function to calculate the area using only the code from the first approach.

In this tutorial, we learned how to calculate the area of ​​a square in two ways. One is using simple statements to multiply and print the result. The other is using a predefined mathematical function called pow() . You can also define a function to calculate the area using only the code from the first approach.

5 ★ | 1 Vote

May be interested