【问题标题】:How to properly use "or" in python? [duplicate]如何在python中正确使用“或”? [复制]
【发布时间】:2019-05-11 22:18:11
【问题描述】:

我正在尝试将变量 numberOfDays 设置为等于该月的天数。但是,elif 语句有一个缺陷。我显然没有正确使用“或”语句,因为当我输入任何内容时,它总是说 numberOfDays 等于 30。

   monthSelection = input("Enter the month you wish to view: ")

   if monthSelection == "February":
        numberOfDays = 28
   elif monthSelection == "April" or "June" or "September" or "November":
        numberOfDays = 30
   else:
        numberOfDays = 31

有没有办法重新格式化这段代码以使其正常工作?

【问题讨论】:

  • 更改为elif monthSelection in ("April", "June", "September", "November"):
  • 这不是陈述,而是逻辑连接;它介于可能是真或假的两件事之间。 a == b or c 表示“a 等于 b,或者 c 是真值”。
  • 除非"September""November" 如果"June" 评估为true,则可能永远不会评估。

标签: python


【解决方案1】:

使用in 而不是or

if monthSelection == "February":
    numberOfDays = 28
elif monthSelection in ("April", "June", "September", "November"):
    numberOfDays = 30
else:
    numberOfDays = 31

否则,您需要分别指定每个相等性:

if monthSelection == "February":
    numberOfDays = 28
elif monthSelection == "April" or monthSelection == "June" or monthSelection == "September" or monthSelection == "November":
    numberOfDays = 30
else:
    numberOfDays = 31

【讨论】:

  • 请始终解释为什么这可以解决问题以及为什么or 不起作用。
  • 让我猜"November" 将是最右边or 的完整表达式并计算为true
猜你喜欢
  • 2013-08-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 2018-11-24
  • 1970-01-01
  • 2021-10-09
  • 2023-01-08
  • 2016-03-09
相关资源
最近更新 更多