Answer:
def convert_units(celsius_value, units):
if units == 0:
return celsius_value
elif units == 1:
return celsius_value * 9/5 + 32
elif units == 2:
return celsius_value + 273.15
else:
return -1 # error code for invalid units input
if __name__ == "__main__":
celsius = float(input("Enter temperature in Celsius: "))
unit = int(input("Enter desired unit of conversion (0 for Celsius, 1 for Fahrenheit, 2 for Kelvin): "))
converted_temp = convert_units(celsius, unit)
if converted_temp == -1:
print("Invalid units input. Please enter 0, 1, or 2.")
else:
print(f"The temperature in {['Celsius', 'Fahrenheit', 'Kelvin'][unit]} is {converted_temp:.2f}.")
Step-by-step explanation:
In the code, we define the convert_units function that takes in a Celsius temperature value (celsius_value) and an integer representing the desired unit of conversion (units). We use a conditional statement to check which conversion is requested and return the temperature value in that unit. If an invalid unit is provided, we return -1 as an error code.
In the if __name__ == "__main__" block, we prompt the user to enter the temperature in Celsius and the desired unit of conversion. We then call the convert_units function with these inputs and store the result in converted_temp. We check if the result is -1 (i.e. an invalid unit was provided) and notify the user of the error. Otherwise, we use an f-string to print the converted temperature with two decimal places and the corresponding unit.
Here are four sample runs of the program:
Enter temperature in Celsius: 25
Enter desired unit of conversion (0 for Celsius, 1 for Fahrenheit, 2 for Kelvin): 1
The temperature in Fahrenheit is 77.00.