![]() |
Functions and if elif problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Functions and if elif problem (/thread-33384.html) |
Functions and if elif problem - Bruizeh - Apr-21-2021 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 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 msgProblem: The function returns Spring every-time, regardless of month. Am I missing something? RE: Functions and if elif problem - ndc85430 - Apr-21-2021 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.
RE: Functions and if elif problem - naughtyCat - Aug-27-2021 ... ![]() 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'))
|