我对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
答案 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中构建的,用于检查给定参数是否在此数组中