Python Forum

Full Version: Functions and if elif problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
Edit: We are not allowed to use lists, in. We are to solve this using if/elif/else
These were the instructions:
Complete the get_season() function which takes a string parameter month. If month is assigned a valid month name, then the function returns the corresponding season (as a string). Otherwise the function returns the string "Undefined - invalid month".

The seasons and their corresponding months are list below:

Spring: September, October, November
Summer: December, January, February
Autumn: March, April, May
Winter: June, July, August
Output:
Expected Output: month = "October" print("Season:", get_season(month)) Result: Season: Spring
This is what I've written:
def get_season(month):
    msg1 = "Spring"
    msg2 = "Summer"
    msg3 = "Autumn"
    msg4 = "Winter"
    msg5 = "Undefined - invalid month"
    msg = ""
    
    if month == "September" or "October" or "November":
        msg = msg1
    elif month == "December" or "January" or "February":
        msg = msg2
    elif month == "March" or "April" or "May":
        msg = msg3
    elif month == "June" or "July" or "May":
        msg = msg4
    else:
        msg = msg5
        
    return msg
Problem:
The function returns Spring every-time, regardless of month. Am I missing something?
Of course it does. On line 9 (and the others really), your condition is wrong. You need to write month == "September" or month == "October" or month == "November".

Non-empty strings evaluate to True, so if month isn't "September", the string "October" is tested and since that evaluates to True (the term used is "truthy") line 10 is executed. See the docs for more info.
... Doh
def get_season(month):
    season = {
        'Spring': ['September', 'October', 'November'],
        'Summer': ['December', 'January', 'February'],
        'Autumn': ['March', 'April', 'May'],
        'Winter': ['June', 'July', 'August']
        }
    key = season.keys()
    for k in key:
        if month in season[k]: return k
    return 'invalid month'

print(get_season('October'))
Output:
Spring