1

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 ?

asked Oct 15, 2012 at 18:26
1
  • 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) Commented Oct 15, 2012 at 19:16

3 Answers 3

7

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

answered Oct 15, 2012 at 18:28
Sign up to request clarification or add additional context in comments.

Comments

2

Are you using python 3.x? If so, input returns a string. bool(youstring) will return True if the string is non-empty.

answered Oct 15, 2012 at 18:28

Comments

1

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
answered Oct 15, 2012 at 18:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.