You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python中if语句多值判断方法及Khan Academy日期验证挑战问题排查

解决你的日期验证问题

嘿,我来帮你搞定这个Khan Academy的Python挑战问题!咱们一步步来梳理:

问题1:错误提示不匹配的原因

你看到的April only has 30 days!其实是Khan Academy平台内置的提示,不是你代码里输出的——因为你的判断条件根本没触发!问题出在这行代码:

if day == 31 and month == not_31_days:

这里你用了==来比较month和整个元组not_31_days,这永远不会成立(一个数字不可能等于包含多个数字的元组),所以你的print("Error. Day must be within the month.")从来没执行过,平台就触发了它自己的错误提示。

修正判断条件

month == not_31_days改成month in not_31_days就对了!in操作符会检查变量是否在给定的集合(这里是元组)里,正好符合你要判断“月份是否是4、6、9、11”的需求。

如何在Python的if语句中判断多个值

针对多个值判断,最常用的两种方式:

  • in操作符(推荐):把所有要判断的值放在元组、列表或集合里,比如:
    not_31_days = (4, 6, 9, 11)
    if month in not_31_days:
        # 执行逻辑
    
    这种方式简洁易读,尤其是值比较多的时候。
  • 用多个or连接:如果值很少,也可以直接写多个判断:
    if month == 4 or month == 6 or month == 9 or month == 11:
        # 执行逻辑
    
    但这种写法在值多的时候会显得冗长,不如in高效。

修正后的完整代码

day = int(input("Enter a day (1-31): "))
if day < 1 or day > 31:
    print("Error. Day must be between 1 and 31.")
month = int(input("Enter a month (1-12): "))
if month < 1 or month > 12:
    print("Error. Month must be between 1 and 12.")
not_31_days = (4, 6, 9, 11)
if day == 31 and month in not_31_days:
    print("Error. Day must be within the month.")

现在当你输入4月31日时,就会输出你预期的错误提示啦!

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

火山引擎 最新活动