Home > OS >  How to count number of Tuesdays in month using for loops?
How to count number of Tuesdays in month using for loops?

Time:04-30

Can somebody advise how to write this code? I'm afraid of making mistakes

n = 30
y = int(input("Tuesday's date:"))

def func(date):
    for y in n:

CodePudding user response:

n = 30
y = int(input("Tuesday's date:"))
def func(date):
    if date <= (n - 28):
        return 5    # In a 30 days month, if the first tuesday is the 1st or #2nd, there will be 5 tuesdays, else 4. If there are 31 days, the first #tuesday can be the 3rd
    return 4  

CodePudding user response:

You can do as follows. for i in range(1, monthrange(now.year, now.month)[1]): loops into each day of the month, than each weekday is compared to weekdaynumber

import datetime
from calendar import monthrange

weekdaynumber=1 #Mon:1, Tue:2, ...

count=0
now = datetime.datetime.now()

for i in range(1, monthrange(now.year, now.month)[1]):
    
    if datetime.date(now.year, now.month, i).weekday() == weekdaynumber:
        count  = 1

print (count)
  • Related