Python Forum
Functions and if elif problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Functions and if elif problem
#1
Question 
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?
Reply
#2
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.
Bruizeh likes this post
Reply
#3
... 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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Simple problem with functions and returns danlopek14q 10 6,619 Mar-17-2021, 05:32 PM
Last Post: danlopek14q
  problem with elif? Osires 5 5,032 Sep-09-2017, 06:33 PM
Last Post: Osires

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020