You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python天气与列车状态判断代码始终输出else,如何修复?

问题原因

你的代码核心问题是输入类型不匹配:input()函数返回的是字符串类型,但你在条件判断里把它和布尔值True/False做比较,这两者永远不会相等,所以无论输入什么,所有条件分支都不满足,最终只会执行else。

比如你输入"False",变量raining实际是字符串"False",而"False" == False的结果是False,第一个if条件不成立,后续elif也都不满足,只能走到else分支。

两种修复方案

方案1:将输入转换为布尔值

通过判断输入的字符串内容,把它转换成对应的布尔值,同时用strip()处理输入前后的空格,避免用户不小心输入空格导致的错误:

raining_input = input("Will it be raining tomorrow? Please enter True or False: ").strip()
# 只有输入"True"时,raining才为True,其他情况(包括输入"False")都为False
raining = raining_input == "True"
trainOnTime = input("Will the train be on time? Please enter Yes, Early or Late: ").strip()

if not raining and trainOnTime == "Yes":
    print("The train is on time you can walk to the train station.")
elif not raining and trainOnTime == "Early":
    print("The train is early you will have to drive to the train station.")
elif raining and trainOnTime == "Late":
    print("It is raining and the train will be late, you will have to drive to work!", str(raining), str(trainOnTime))
else:
    print("Invalid entry, please try again!")
input('Press ENTER to exit')

方案2:直接比较字符串

把条件判断里的布尔值True/False改成对应的字符串"True"/"False",直接和输入的字符串做比较:

raining = input("Will it be raining tomorrow? Please enter True or False: ").strip()
trainOnTime = input("Will the train be on time? Please enter Yes, Early or Late: ").strip()

if raining == "False" and trainOnTime == "Yes":
    print("The train is on time you can walk to the train station.")
elif raining == "False" and trainOnTime == "Early":
    print("The train is early you will have to drive to the train station.")
elif raining == "True" and trainOnTime == "Late":
    print("It is raining and the train will be late, you will have to drive to work!", raining, trainOnTime)
else:
    print("Invalid entry, please try again!")
input('Press ENTER to exit')
额外提示

建议加上strip()处理输入,避免用户输入时不小心带了空格(比如" False ")导致判断失败,这样程序的容错性会更好。

内容的提问来源于stack exchange,提问作者CJDev2013

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 09:13:17