Please help i want to be able to do this better since im just learning python and i need to know this for school.
import datetime
TheDate = datetime.date.today()
ExpireDate = 0,0,0
Variable = datetime.date(ExpireDate)
ExpireDate = input("When does your card expire? (Year,Month,Day)" )
if Variable > TheDate:
print("Your card has not expired")
else
print("Your card has expired")
CodePudding user response:
You have to get the input from the user before you can assign your Variable
with the values that the user inputs.
Furthermore, you have to give datetime.date()
the attributes it needs (year, month, date).
import datetime
TheDate = datetime.date.today()
ExpireDate = input("When does your card expire? (Year,Month,Day)" )
Variable = datetime.date(*[eval(x) for x in ExpireDate.split(',')])
if Variable > TheDate:
print("Your card has not expired")
else:
print("Your card has expired")
That *[eval(x) for x in ExpireDate.split(',')]
bit can be explained as:
ExpireDate.split(',')
splits the user input by comma into a list. The year, month, and date then exist in the newly created list ['2020','10','14']
as an example.
Those are strings, but we need integers for the datetime.date()
method so we convert to integer using list comprehension and the eval()
function: [eval(x) for x in <the list>]
. The list will then look like [2020,10,14]
, which is nice an integery.
Lastly we toss a *
in front of that thing which tells python to take each value in the list and use it as a parameter in the datetime.date()
function call.
Longer form:
import datetime
TheDate = datetime.date.today()
ExpireDate = input("When does your card expire? (Year,Month,Day)" )
ExpireDateList = ExpireDate.split(',')
ExpireDateIntList = []
for x in ExpireDateList:
ExpireDateIntList.append(eval(x))
Variable = datetime.date(ExpireDateIntList[0],ExpireDateIntList[1],ExpireDateIntList[2])
if Variable > TheDate:
print("Your card has not expired")
else:
print("Your card has expired")
CodePudding user response:
Here is a working version i was able to put together:
import datetime
TheDate = datetime.date.today()
ExpireDate = 1,1,1
Variable = datetime.date(*ExpireDate)
ExpireDate = input("When does your card expire? (Year,Month,Day)" )
if Variable > TheDate:
print("Your card has not expired")
else:
print("Your card has expired")
But also note that:
ExpireDate = 1,1,1
Variable = datetime.date(*ExpireDate)
can just be replaced with:
Variable = datetime.date.min
But actually, here is what I think you want to do:
import datetime
TheDate = datetime.date.today()
ExpireDate = input("When does your card expire? (Year, Month, Day) ")
Variable = datetime.date(*map(int, ExpireDate.replace(' ', '').split(',')))
if Variable > TheDate:
print("Your card has not expired")
else:
print("Your card has expired")
Here is a sample playthrough:
When does your card expire? (Year, Month, Day) 2022, 9, 2
Your card has not expired