Write a python program to convert hours into days


The python program defines a HoursToDaysConverter class, which is used to convert a number of hours into days. Here's a breakdown of the code:

  • class HoursToDaysConverter: This class represents a converter for converting hours into days. It has an __init__ method to initialize the hours attribute and a convert_to_days method to perform the conversion.
  • In the try block, the code attempts to get the number of hours from the user using the input function. It converts the user input to a float and assigns it to the hours_input variable. If the user enters an invalid input (not a number), a ValueError exception is raised, and an error message is printed.
  • If the user enters a valid number of hours, an instance of the HoursToDaysConverter class is created using the hours_input, and the convert_to_days method is called to perform the conversion.
  • The result, which is the number of days, is stored in the days_result variable.
  • Finally, the code prints the original number of hours entered by the user and the equivalent number of days based on the conversion.

Here's what the code does:

  • It takes a user input for the number of hours and attempts to convert it to a float.
  • If the input is valid, it converts the number of hours to days using the HoursToDaysConverter class.
  • It then displays the original number of hours and the equivalent number of days.

Source Code

class HoursToDaysConverter:
    def __init__(self, hours):
        self.hours = hours
 
    def convert_to_days(self):
        days = self.hours / 24
        return days
try:
    hours_input = float(input("Enter the Number of Hours : "))# Get the number of hours from the user
except ValueError:
    print("Invalid input. Please enter a valid number of hours.")
else:    
    obj = HoursToDaysConverter(hours_input) # Create an instance of the HoursToDaysConverter class
    days_result = obj.convert_to_days() #Call the Convert hours to days method   
    print(hours_input, "hours is equal to", days_result, "days.") # Display the result

Output

Enter the Number of Hours : 52
52.0 hours is equal to 2.1666666666666665 days.

Example Programs