简单的Python函数

Cha*_*gaD 1 python

我做了简单的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"
Run Code Online (Sandbox Code Playgroud)

测试数据 -

>>> 
Is it raining ? 0
What is the temp ? 43
Umbrella
>>> ================================ RESTART ================================
>>> 
Is it raining ? 1
What is the temp ? 43
Umbrella
>>> 
Run Code Online (Sandbox Code Playgroud)

如果下雨是假的,它就会给予sh Sweateror Cap.但我的代码提供了真实的,即使israining_str == 0israining_str == 1

我在哪里做错了?

Bre*_*arn 7

这是你的问题:

>>> bool("0")
True
Run Code Online (Sandbox Code Playgroud)

转换为布尔值时,任何非空字符串都为True.您可以bool(int(israining_str))转换为int然后bool,如果此人输入字符串,将为您提供数字零"0".