What season is this month in?
Watch this video to learn about the new concepts shown in the program:
The new commands used in this program and others that may be useful. Select them below to learn more:
match, case, case _match
Provides an alternative structure to if, elif, else and is used in situations where there are more than two possibilities. There are also more advanced uses of match that make it more useful than if. You need to be using Python 3.10 or higher to use the match command. Don’t forget the colon at the end of the match statement.
case
Is the value for the match command. Possibilities for the value can be separated with pipe characters: |. You can have as many case statements as you need. Don’t forget the colon at the end of the case statement.
case _
An underscore is a special condition that is the same as else. It captures anything else that was not matched by the previous case statements. Don’t forget the colon at the end of the case statement.
Questions to think about with this program to check your understanding:
In line 25: print("Month", month, "is in the", season) why is the word month written twice in this line, but it is only output once?
“Month” in double quotes is a string, it is the actual word, “Month”. In contrast, month without the double quotes is a variable: an area in memory to hold data that can change. This is holding the name of the month the user inputs. E.g. “May”. As we want the word “Month” followed by the name of the month to be output we need both in the statement.
How could line 8 be written using an if instead of case?
if month == "December" or month == "January" or month == "February":
Change the program so that:
seasons handles the input of the month as a number too. E.g. At the prompt, “Enter the month: “, the user could enter “5” for May instead.Enter the number of the month: 5
Month 5 is in the Spring
# Seasons program
# -------------------------
# Subprograms
# -------------------------
# Return which season a month is in
def seasons(month):
---
match month:
---
# Winter months
---
case "December" | "12" | "January" | "1" | "February" | "2":
---
return "Winter"
---
# Spring months
---
case "March" | "3" | "April" | "4" | "May" | "5":
---
return "Spring"
---
# Summer months
---
case "June" | "6" | "July" | "7" | "August" | "8":
---
return "Summer"
---
# Autumn months
---
case "September" | "9" | "October" | "10" | "November" | "11":
---
return "Autumn"
---
# Not a valid month
---
case _:
---
return "Error"
---
# -------------------------
# Main program
# -------------------------
---
month = input("Enter the month: ")
---
season = seasons(month)
---
print("Month", month, "is in the", season)