In this program we will calculate the area of a rectangle when we know its length and breadth. The basic formula to calculate the area of a rectangle is to multiply its length to its breadth. We will do the same thing by writing some code.
To understand this program, you should have the knowledge of –
- input function
- int function
- float function
- arithmetic operators
Sample program one (By assigning int values manually)
In this program we are assigning the values of length and breadth ourselves.
r_length = 15 r_breadth = 18 r_area = r_length * r_breadth print("The area is ", r_area)
The area is 270
- In here we have declared two variables named r_length and r_breadth and initialized them with 15 and 18 respectively.
- Next we have declared a variable named r_area and stored the multiplication of the two values in it. The multiplication is calculated by using the * operator.
- Lastly we have displayed the calculated value with the help of print function.
Sample program Two (By taking input values from user)
In this program, we have done the same thing, but in a bit different manner. In this program we have taken the input values(length and breadth of rectangle) from the user instead of assigning them ourselves.
r_length = int(input("Enter the length")) r_breadth = int(input("Enter the breadth")) r_area = r_length * r_breadth print("The area is ", r_area)
Enter the length4
Enter the breadth7
The area is 28
Note : We have used the int function to convert the input string to its equivalent integer value. As we are going through programs, by now you should know what int function is used for. If you don’t, go through our python tutorials.
Sample program Three (By taking float values from user)
In this program, we are allowing the user to give float(values containing decimal) values as well by using the float function. Unlike the int function, the float function casts or converts the input string to equivalent float value.
r_length = float(input("Enter the length")) r_breadth = float(input("Enter the breadth")) r_area = r_length * r_breadth print("The area is ", r_area)
Enter the length4.5
Enter the breadth2.4
The area is 10.8