ChamingaD ChamingaD - 6 months ago 22
Python Question

Simple Python Function

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"
return "Cap"

Test data -

Is it raining ? 0
What is the temp ? 43
>>> ================================ RESTART ================================
Is it raining ? 1
What is the temp ? 43

If raining is false it shroud give
. But my code gives true even
israining_str == 0
israining_str == 1

Where am i doing wrong ?

Answer Source

Here is your problem:

>>> bool("0")

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".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download