Answer the question
In order to leave comments, you need to log in
How can one shorten/optimize such Python code?
Hello. Please tell the student how this code can be shortened. Thank you.
month = int(input())
if month == 1 or month == 2 or month == 12:
print('зима')
elif month == 3 or month == 4 or month == 5:
print('весна')
elif month == 6 or month == 7 or month == 8:
print('лето')
elif month == 9 or month == 10 or month == 11:
print('осень')
else:
print('error')
Answer the question
In order to leave comments, you need to log in
using a dictionary will help to reduce the code significantly:
month = int(input())
seasons = {0:'зима', 1:'весна', 2:'лето', 3:'осень', 4:'зима'}
if 1 <= month <= 12: print(seasons[month//3])
else: print('error')
seasons = ['зима', 'весна', 'лето', 'осень', 'зима']
month = int(input())
seasons = {
'winter': (1, 2, 12),
'spring': (3, 4, 5),
'summer': (6, 7, 8),
'autumn': (9, 10, 11)
}
result = 'error'
for name, monthes in seasons.items():
if month in monthes:
result = name
break
print(result)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question