The most common answer is:
def convert_C_to_F(c):
f = ((1.8*c) + 32)
return float(f)
Now write your function for converting Fahrenheit to Celcius.
def convert_F_to_C(f):
c = ((f-32) / 1.8)
return float(c)
try:
x = float(input())
except ValueError:
print(“An error has occured”)
try:
y = float(input())
except ValueError:
print(“An error has occured”)
print(convert_C_to_F(x))
Change 100C to F:
print(convert_C_to_F(y))
To make your Temperature Converter function correctly and handle user input more clearly, including converting Celsius to Fahrenheit and vice versa, let’s organize and correct your code.
Additionally, it seems there’s some confusion in the user input part, as it doesn’t specify what the input is for.
Let’s also address that by adding prompts to the input function calls:
# Converts Celsius to Fahrenheit
def convert_C_to_F(c):
f = ((1.8 * c) + 32)
return float(f)
# Converts Fahrenheit to Celsius
def convert_F_to_C(f):
c = ((f - 32) / 1.8)
return float(c)
# Attempt to get Celsius input from the user
try:
celsius = float(input("Enter a temperature in Celsius: "))
print(f"{celsius}C is {convert_C_to_F(celsius)}F")
except ValueError:
print("An error has occurred")
# Attempt to get Fahrenheit input from the user
try:
fahrenheit = float(input("Enter a temperature in Fahrenheit: "))
print(f"{fahrenheit}F is {convert_F_to_C(fahrenheit)}C")
except ValueError:
print("An error has occurred")
This corrected and enhanced code:
- Clearly prompts the user for a temperature in Celsius, attempts to convert it to Fahrenheit, and prints the result.
- Similarly, it prompts for a temperature in Fahrenheit, converts it to Celsius, and prints the outcome.
- Uses
try-except
blocks to catchValueError
in case of non-numeric input, printing an error message if such an exception occurs. - Demonstrates the use of the functions
convert_C_to_F
andconvert_F_to_C
for temperature conversions.