我的口译员不承认12月是冬季月份(如果/其他)

时间:2016-12-28 00:00:15

标签: python if-statement pycharm

我对Python很新。我正在使用PyCharm进行练习。当我输入" 12月"在月份的输入中,口译员将12月视为秋季月份。为什么会这样? (如果你不明白我的意思,请查看底部)

Winter = ['December', 'January', 'February']
Spring = ['March', 'April', 'May']
Summer = ['June', 'July', 'August']
Autumn = ['September', 'October', 'November']

month = input('What is the current month? ')

if month == Winter:
    print('%s is in the Winter' % month)

elif month == Spring:
    print('%s is in the Spring' % month)

elif month == Summer:
    print('%s is in the Summer' % month)

else:
    print('%s is in the Autumn' % month)

What is the current month? December
December is in the Autumn

3 个答案:

答案 0 :(得分:2)

示例中的month是一个字符串(而不是列表),因此您无法将其与列表进行比较。您可以使用var1 in list1

检查列表中是否存在月份
Winter = ['December', 'January', 'February']
Spring = ['March', 'April', 'May']
Summer = ['June', 'July', 'August']
Autumn = ['September', 'October', 'November']

month = input('What is the current month? ')

if month in Winter:
    print('%s is in the Winter' % month)

elif month in Spring:
    print('%s is in the Spring' % month)

elif month in Summer:
    print('%s is in the Summer' % month)

else:
    print('%s is in the Autumn' % month)

What is the current month? December
December is in the Winter

答案 1 :(得分:1)

不考虑==in错误,您的代码有一个缺陷,即在else条款中合并一个月的秋天与未被识别。即使在第一次更正之后,也应该有4个if子句,然后是错误条目的else子句。我会让你相应地修改Dekel的答案。

对于所提出的问题,查看一个月的季节,您可以使用dict

wi, sp, su, au = 'Winter', 'Spring', 'Summer', 'Autumn'
season = {'December': wi, 'January': wi, 'February': wi,
           'March': sp, 'April': sp, 'May': sp,
           'June': su, 'July': su, 'August': su,
           'September': au, 'October': au, 'November': au}
month = input('Enter a month: ')
try:
    print('{} is in {}'.format(month, season[month]))
except KeyError:
    print('{} is not recognized'.format(month))

要更灵活地输入大写,请将输入行更改为

month = input('Enter a month: ').lower()

并小写season中的月份。

答案 2 :(得分:0)

当你写“if month == Winter:”时,你现在检查来自用户的输入是否是数组相等的冬季数组然后他检查另一个if语句然后输入else语句并打印“print('%s是在秋天'%月')代码应该写:

Winter = ['December', 'January', 'February']
Spring = ['March', 'April', 'May']
Summer = ['June', 'July', 'August']
Autumn = ['September', 'October', 'November']

month = raw_input('What is the current month? ')

if Winter.__contains__(month):
    print('%s is in the Winter' % month)

elif Spring.__contains__(month):
    print('%s is in the Spring' % month)

elif Summer.__contains__(month):
    print('%s is in the Summer' % month)

else:
    print('%s is in the Autumn' % month)

包含是在python中构建的,用于检查给定参数是否在此数组中