One of the most common calculations in science and engineering is the conversion of temperature between Celsius and Fahrenheit. In this article, we will discuss different ways to write a Python program to convert temperatures between Celsius and Fahrenheit using functions, classes, and loops.
Python program to convert celsius to fahrenheit and fahrenheit to celsius
python program to convert celsius to fahrenheit with exception handling
This Python program converts a temperature from Celsius to Fahrenheit. The user is prompted to enter a temperature in Celsius, which is then passed as an argument to a function called celsius_to_fahrenheit. The function performs the conversion and returns the result in Fahrenheit. The program also includes exception handling, which is used to catch any errors that may occur during the execution of the program. Specifically, the function raises a ValueError exception if the input temperature is below absolute zero. The try and except blocks are used to catch this exception and display an error message to the user.
# python program to convert celsius to fahrenheit with exception handlingdef celsius_to_fahrenheit(celsius):#convert celsius to fahrenheitif celsius <-273.15:raiseValueError("Temperature below absolute zero")else:
fahrenheit =(celsius *9/5)+32return fahrenheit
try:
celsius =float(input("Enter temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)print("Temperature in Fahrenheit: {:.2f}".format(fahrenheit))exceptValueErroras e:print(e)