Python Program to Convert temperatures using Classes
In this example, we will write a python program to convert temperatures in Celcius and Fahrenheit scale using class and objects. To better understand this example, make sure you have knowledge of the following tutorials:-
Conversion Formula for Temperature conversion
C = (F – 32) * 5/9
F = (C * 9/5) + 32
Python Program to Convert temperatures using Classes
class Temperature: temp = 0 def __init__(self, temp): self.temp = temp def convert_to_fahrenheit(self): result = float((9 * self.temp) / 5 + 32) return result def convert_to_celsius(self): result = float((self.temp - 32) * 5 / 9) return result input_temp = float(input("Input temperature in celsius: ")) temp1 = Temperature(input_temp) print(temp1.convert_to_fahrenheit()) input_temp = float(input("Input temperature in fahrenheit: ")) temp1 = Temperature(input_temp) print(temp1.convert_to_celsius())
The output of the above program is:-
Input temperature in celsius: 37
98.6
Input temperature in fahrenheit: 98.6
37.0
98.6
Input temperature in fahrenheit: 98.6
37.0
Program Explanation
Here we have created a class named “Temperature” that has one attribute temperature. The constructor of the class initiates the temp attributes using __init__ function. Two methods are defined as “convert_to_fahrenheit” and “convert_to_fahrenheit” to convert the temperatures. Once the class has been defined, we take inputs from the user as the temperature in Celcius and Fahrenheit An instance of the class “Temperature” is created as “temp1” and “temp2 and the method is invoked to display the output in the converted form of temperature.