我做了一个简单的 python 函数,它接受两个输入并输出一些文本。
在这里,
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"
测试数据-
>>>
Is it raining ? 0
What is the temp ? 43
Umbrella
>>> ================================ RESTART ================================
>>>
Is it raining ? 1
What is the temp ? 43
Umbrella
>>>
如果下雨是假的,它会给 Sweater 或 Cap 裹尸布。但我的代码给出了 true 甚至 israining_str == 0 或 israining_str == 1
我哪里做错了?
请您参考如下方法:
这是你的问题:
>>> bool("0")
True
任何非空字符串在转换为 bool 值时都为 True。你可以做 bool(int(israining_str)) 转换为 int 然后 bool,如果这个人输入,这会给你数字零字符串 "0"。
