Reputation: 61
So, I've been having a problem while trying to convert the variable t into a float, and it's giving me an error, saying "could not convert string to float: " with a space as false.
def FtoC(a):
a=(t-32)*1.8
return a
def FtoK(a):
a=(a-32)*1.8+273
return ta
def CtoF(a):
a=a*1.8+32
return a
def CtoK(a):
a=a+273
return t
def KtoC(a):
a=a-273
return a
def KtoF(a):
a=(a+459.67)*5/9
return a
########################################################
import re
t=input()
while True:
if t=='end':
break
tl=list(t)
t=re.findall('\d+', t)
t=''.join(t)
t=float(t)
if tl[-1]!='C' or tl[-1]!='K' or tl[-1]!='F' or t>200 or t<-100:
print("Wrong")
else:
if tl[-1]=='C':
print("%.2f" % t,'C',CtoF(t),'F',CtoK(t),'K')
if tl[-1]=='K':
print("%.2f" % t,'K',KtoC(t),'C',KtoF(t),'F')
if tl[-1]=='F':
print("%.2f" % t,'F',FtoC(t),'C',FtoK(t),'K')
t=input()
I've been testing out with print commands inbetween and it prints the float value just alright, but in the if command it shows up an error, so it just prints "Wrong" every single time. When I remove:
if tl[-1]!='C' or tl[-1]!='K' or tl[-1]!='F' or t>200 or t<-100:
print("Wrong")
The code works jus fine. Where is the problem?
I've been running the program on a private university platform, and this is what it returns:
Non-zero exitcode 1
*** Program stderr output following ***
Traceback (most recent call last):
File "my_code.py3", line 28, in
t=float(t)
ValueError: could not convert string to float:
When using Python it just prints "Wrong", without any error.
Upvotes: 1
Views: 4221
Reputation: 343
Your problem isn't with converting to a float but with your condition.
write out the truth table and you'll find your mistake.
As a side note it's quite confusing using negation in a condition unless it's absolutely necessary.
try using the condition:
allowed_scales = ["C", "K", "F"]
if tl[-1] in allowed_scales and -100<t<200:
# do your work here
else:
print("wrong")
You also have a problem with your regex cutting out any minus signs so you will never get a negative temperature.
You should probably also check that the input actually contains some digits to convert to a float as trying to convert an empty string ""
will return the error you are seeing.
while True:
# in python 2:
t = raw_input()
# in python 3:
t = input()
if t=='end':
break
try:
t=float(t[:-1]) # -1 to cut off the scale type
except ValueError:
print("Not valid input. try again.")
allowed_scales = ["C", "K", "F"]
if tl[-1] in allowed_scales and -100<t<200:
if tl[-1]=='C':
print("%.2f" % t,'C',CtoF(t),'F',CtoK(t),'K')
if tl[-1]=='K':
print("%.2f" % t,'K',KtoC(t),'C',KtoF(t),'F')
if tl[-1]=='F':
print("%.2f" % t,'F',FtoC(t),'C',FtoK(t),'K')
else:
print("wrong")
working with user input is always tricky since they can always type whatever they want in the box. using a try-except will handle most user error in this case.
Upvotes: 1