0

I've just started learning Python and am setting myself the challenge of trying to create practical little programs that do something. I created a dictionary with months of the year and corresponding average temperatures. I ask the user what month they'd like to choose and then display the temperature for that month.

However it seems like I am re-writing a lot of the same code, but just changing the months. Can someone advise alternate, more efficient ways of achieving this?

# This program shows the average temperature for the month you have chosen

dict = {'january': 10, 'february': 10, 'march': 12, 'april': 14, 'may': 18, 'june': 21, 'july': 25, 'august': 25, 'september': 21, 'october': 18, 'november': 14, 'december': 11,}

month = input('When are you visting Majorca? \nChoose month: ')
if month == 'january':
    print ('In january the average temperature will be: ')
    print (dict['january'] , 'degrees celsius')
if month == 'february':
    print ('In february the average temperature will be: ')
    print (dict['february'] , 'degrees celsius')
Carlos Cavero
  • 3,011
  • 5
  • 21
  • 41
sandhun
  • 5
  • 2

1 Answers1

0

This is how I'd do it:

dict = {'January': 10, 'February': 10, 'March': 12, 'April': 14, 'May': 18, 'June': 21, 'July': 25, 'August': 25, 'September': 21, 'October': 18, 'November': 14, 'December': 11,}

month = input('When are you visiting Mallorca? \nChoose month: ')
temp = dict.get(month, None)
if temp:
    print('In {} the average temperature will be: {} degrees Celsius'.format(month, temp))
else:
    print("You didn't enter a valid month!")

I'd suggest you to read about dict.get() method here and about string formatting here. You could replace None with False, but the logic would remain the same. Also, notice the capitalization of names of the months and Celsius, and spelling the name of Mallorca ;)

EDIT:

As of Python 3.6 you can use formatted string literals instead of str.format(), see the official docs for more detail (thanks to @Andy for pointing this out). The print statement in the if block would then be:

print(f'In {month} the average temperature will be: {temp} degrees Celsius')
gstukelj
  • 2,291
  • 1
  • 7
  • 20
  • Thanks, that was really useful. Your way is so much better. I don't understand it (yet) but will be sure to learn about the things you suggested. Majorca is the British spelling, either way it doesn't really matter as it's just a practice scenario. – sandhun Oct 25 '19 at 18:42
  • 1
    @sandhun note that this uses old-style strings, check out f-strings as well for even cleaner code. – Andy Oct 25 '19 at 19:38
  • @sandhun I hate to say it, but if it answered your question you could accept the answer or upvote it:) – gstukelj Oct 26 '19 at 16:04
  • @gst Apologies, have done so now. F strings make things so much easier. – sandhun Oct 27 '19 at 09:35