How to create a Friday 13th detector
In the Gregorian calendar, Friday the 13th is considered the unluckiest day and is tied to misfortunate circumstances. Each year, Friday the 13th occurs one to three times.
Let us discover how to detect if a Friday 13th falls out in a particular month of a given year.
Code
import datetimeimport calendardef detect_Friday_13(year,month):#Get the thirteen day of the monthday_13_of_the_month = datetime.date(year,month,13)print("The thirteenth day of month {} and year {} is a {}.".format(month,year,day_13_of_the_month.strftime("%A")))if day_13_of_the_month.weekday() == 4:return Truereturn Falsedetect_Friday_13(year=2023,month=3)detect_Friday_13(year=2024,month=12)
Explanation
Now, let us go through the code above:
Lines 1–2: We import the required Python libraries.
Line 4: We define a function aiming to check if the thirteenth day of a given year and month is a Friday.
Line 6: We get the date of the thirteenth day of the given year and month and store it in the variable
day_13_of_the_month.Line 7: We display a message showing the day name of the
day_13_of_the_monthvariable using the methodstrftime.Lines 8–10: We extract the day of the week as an integer value out of the
day_13_of_the_monthvariable nd check if it is equal to 4 (Friday). If this is the case returnTrueelse returnFalse.Lines 12–13: We call the function
detect_Friday_13and check the output generated.
Free Resources