D
D
Dmitry2018-10-24 19:47:48
Python
Dmitry, 2018-10-24 19:47:48

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

2 answer(s)
D
Dmitry, 2018-10-24
@provocatorr

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')

if you are not already familiar with dictionaries, you can use a similar list in the second line
seasons = ['зима', 'весна', 'лето', 'осень', 'зима']

V
Vadim Shatalov, 2018-10-24
@netpastor

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 question

Ask a Question

731 491 924 answers to any question