I did simple python function which takes two inputs and output some text.
Here it is,
def weather():
israining_str=input("Is it raining (1 or 0) ? ")
israining = bool(israining_str)
temp_str=input("What is the temp ? ")
temp = float(temp_str)
if israining==True and temp<18:
return "Umbrella & Sweater"
elif israining==True and temp>=18:
return "Umbrella"
elif israining==False and temp<18:
return "Sweater"
else:
return "Cap"
Test data -
>>>
Is it raining ? 0
What is the temp ? 43
Umbrella
>>> ================================ RESTART ================================
>>>
Is it raining ? 1
What is the temp ? 43
Umbrella
>>>
If raining is false it shroud give Sweater or Cap. But my code gives true even israining_str == 0 or israining_str == 1
Where am i doing wrong ?
-
Comment, testing directly for bool values by comparing with True or False is not a very good style, since you can write "if israining:". with the equivalent meaning to "if bool(israining) == True:" - but being shorter and clearer. (likewise you should write "if not israining:" in the third branch)Joe M.– Joe M.2012年10月15日 19:16:35 +00:00Commented Oct 15, 2012 at 19:16
3 Answers 3
Here is your problem:
>>> bool("0")
True
Any nonempty string is True when converted to a boolean. You could do bool(int(israining_str)) to convert to int and then bool, which will give you the number zero if the person inputs the string "0".
Comments
Are you using python 3.x? If so, input returns a string. bool(youstring) will return True if the string is non-empty.
Comments
According to python's documentation:
bool(x)
Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False.
You pass non-empty string to this function, non-empty string is True.
You can write something like that:
t = int(israining_str)
# here you can check if user's input is 0 or 1 and ask user again if it is not
israining = False
if t:
israining = True