n00b.py
n00b.py

Reputation: 43

How do I write two variable dates in a function?

For an exercise, I'm supposed to write a function with two dates as variable inputs and compare them. However, whatever way I try to define the function, it gives me an invalid syntax.

I'm trying to do something like this:

from datetime import date

def birthday(date(year1, month1, day1), date(year2, month2, day2)):
    party = False
    if month1 == month2 and day1 == day2:
        party = True

    return party

It is intended that the function be called like this:

birthday(date(1969, 10, 5), date(2015, 10, 5))

Upvotes: 1

Views: 90

Answers (3)

Mostafa Babaii
Mostafa Babaii

Reputation: 158

if you want to compare month and day from 2 dates to check birthday, try blow code:

from datetime import date

def bd(d1: date, d2: date) -> bool:
    return d1.month == d2.month and d1.day == d2.day

print(bd(date(1989, 8, 11), date(2019, 8, 11)))

Upvotes: 1

Hampi
Hampi

Reputation: 11

Well, question is not clear but you can do it in this way:

from datetime import date

def birthday(date1,date2):
    party = False
    if date1.month == date2.month and date1.day == date2.day:
        party = True

    return party

date1= date(2019, 4, 13)
date2= date(2019, 4, 13)

print(birthday(date1,date2))

Output:

True

Upvotes: 1

Andrew Morton
Andrew Morton

Reputation: 25013

You don't declare the components of the dates in the function arguments because it they are ready-made dates being passed to it, as shown in the examples given, such as

birthday(date(1969, 10, 5), date(2015, 10, 5))

So you just need to:

import datetime
from datetime import date

def birthday(date1, date2):
    party = False

    if date1.month == date2.month and date1.day == date2.day:
        party = True

    return party

Then you can do

bd1 = date(2000, 10, 20)
bd2 = date(2008, 10, 20)
bd3 = date(2000, 10, 1)

print(birthday(bd1, bd2))
print(birthday(bd1, bd3))

And get the output

True
False

(You might not need the import datetime: I did.)

You could even shorten the function to

def birthday(date1, date2):
    return date1.month == date2.month and date1.day == date2.day

Upvotes: 1

Related Questions