I’m trying to make a temperature converter. It convert Celsius to Fahrenheit and vice versa. The code I wrote is:
user_input = input("Insert the temperature you would like to convert: ")
user_num = user_input.replace('F' or 'C', '')
user_temp = float(user_num)
if ('F' in user_input or 'f' in user_input):
print(((user_temp - 32) * 5/9), 'C') # conversion from F to C
elif ('C' in user_input or 'c' in user_input):
print(((user_temp * 9/5) + 32), 'F') # conversion fron C to F
else:
print("Try again.")
I can convert Fahrenheit to Celsius, but can’t do the opposite.
When I try to convert c to f i get
user_temp = float(user_num) ValueError: could not convert string to float: '36C'
Also, I want to make the code so it replaces either ‘F’ or ‘f’ and ‘C’ or ‘c’.
What I can fix in order to make this work?
>Solution :
'F' or 'C' just evaluates to 'F'. I don’t think this is what you want. You can either replace twice:
user_num = user_input.replace('F', '').replace('C', '')
or use a RegEx:
import re
user_num = re.sub('F|C', '', user_input)
I think your later 'f' and 'c' should probably be capitalised.