【问题标题】:Why does every month return 31? [closed]为什么每个月都返回 31? [关闭]
【发布时间】:2020-07-30 22:50:31
【问题描述】:

我的代码运行良好,但如果出现拼写错误,所有月份都会返回 31 天。我该如何纠正这个问题?

month= input ("Enter month :  ")
days = 31 

if month == "April" or month == "June" or month == "September" or month == "November" :
  days = 30 
elif month == "February" :      
  days = "28 or 29"

print(days)

【问题讨论】:

  • 你在输入什么?如果我输入April,我会得到30
  • 您的代码没有输入任何 if 语句
  • 你输入的是April还是april?尝试使用str.lower并在代码中使用小写
  • 也代替所有那些or 语句。为什么不使用if month in {"April", "June", "September", "November"}:
  • 那么你运行的代码不是你发布的代码。由于发布的代码工作正常。

标签: python days


【解决方案1】:

我怀疑错误是您输入月份的方式。在您的代码中,输入区分大小写。所以需要输入AprilMarch等。

您可以通过清理输入字符串(例如,去除空格并转换为小写)和使用in 语句来改进您的代码。

month = input("Enter month :  ")
month = month.strip()  # strip whitespace on either end of the string.
month = month.lower()  # convert to lowercase.
days = 31

if month in {"april", "june", "september", "november"}:
    days = 30
elif month == "february":
    days = "28 or 29"
    
print(days)

在上面的代码中,{"april", "june", "september", "november"} 是一个set。可以快速查找值是否在 set 中。

【讨论】:

  • 与2月比较时还需要month.lower()
  • 谢谢@Barmar。固定。
  • 我输入的是 April, June January...等
【解决方案2】:

按照 jakub 的建议使用小写(巧合的是,与我的名字相同),您只需要月份的前三个字母。这将有助于防止拼写错误。例如,有人可能将二月拼错为二月。如果还想检查前三个字母的拼写错误,可以使用 while 循环:

spelled_correctly = False
while not spelled_correctly:
    month = input('Enter month : ')
    month = month.lower()[:3]  # convert to lowercase
    if month in {'apr', 'jun', 'sep', 'nov'}:
        days = 30
        spelled_correctly = True
    elif month in {'jan', 'mar', 'may', 'jul', 'aug', 'oct', 'dec'}:
        days = 31
        spelled_correctly = True
    elif month == 'feb':
        days = '28 or 29'
        spelled_correctly = True
    elif month == '':
        days = 'Goodbye' # or whatever option you like
        spelled_correctly = True
    else:
        print('Month mispelled. Try again. Or press enter to quit.')
        spelled_correctly = False
print(days)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    相关资源
    最近更新 更多