Exercise
Object Array: Tables
Objective
Develop a Python class called "Table". The class should include a constructor to initialize the width and height of the table. It should also have a method named "ShowData" that prints the table’s dimensions. Then, create an array with 10 tables, each having random dimensions ranging from 50 cm to 200 cm. Finally, display the information for each table in the array.
Example Python Exercise
Show Python Code
import random # Importing the random module to generate random dimensions
# Table class with width and height attributes
class Table:
def __init__(self, width, height):
self.width = width # Width of the table
self.height = height # Height of the table
# Method to display the table's dimensions
def ShowData(self):
print(f"Table dimensions - Width: {self.width} cm, Height: {self.height} cm")
# Main program to create an array of 10 tables with random dimensions
if __name__ == "__main__":
tables = [] # List to store the tables
# Create 10 tables with random width and height between 50 and 200 cm
for _ in range(10):
width = random.randint(50, 200) # Random width between 50 and 200 cm
height = random.randint(50, 200) # Random height between 50 and 200 cm
table = Table(width, height) # Create a new Table object
tables.append(table) # Add the table to the list
# Display the information for each table in the array
print("Table Information:")
for table in tables:
table.ShowData() # Call the ShowData method to display the table's dimensions
Output
Table Information:
Table dimensions - Width: 157 cm, Height: 104 cm
Table dimensions - Width: 158 cm, Height: 112 cm
Table dimensions - Width: 172 cm, Height: 60 cm
Table dimensions - Width: 103 cm, Height: 138 cm
Table dimensions - Width: 141 cm, Height: 173 cm
Table dimensions - Width: 69 cm, Height: 148 cm
Table dimensions - Width: 187 cm, Height: 138 cm
Table dimensions - Width: 56 cm, Height: 148 cm
Table dimensions - Width: 110 cm, Height: 114 cm
Table dimensions - Width: 183 cm, Height: 161 cm
Share this Python Exercise