我对这一切都很陌生,现在我正试图让两个函数执行和打印,但我似乎无法掌握它:
import datetime
def get_date(prompt):
while True:
user_input = raw_input(prompt)
try:
user_date = datetime.datetime.strptime(user_input, "%m-%d")
break
except Exception as e:
print "There was an error:", e
print "Please enter a date"
return user_date.date()
def checkNight(date):
date = datetime.strptime('2011-'+date, '%Y-%m-%d').strftime('$A')
birthday = get_date("Please enter your birthday (MM-DD): ")
another_date = get_date("Please enter another date (MM-DD): ")
if birthday > another_date:
print "Your friend's birthday comes first!"
print checkNight(date)
elif birthday < another_date:
print "Your birthday comes first!"
print checkNight(date)
else:
print "You and your friend can celebrate together."
函数get_date
需要能够检查日期是否有5个字符并允许拆分为任何内容。如果有人输入“02-29”,它会将其视为“02-28”。 checkNight
需要能够检查生日早期的哪个晚上。
以下是一些例子:
Please enter your birthday (MM-DD): 11-25 Please enter a friend's birthday (MM-DD): 03-05 Your friend's birthday comes first! Great! The party is on Saturday, a weekend night. Please enter your birthday (MM-DD): 03-02 Please enter a friend's birthday (MM-DD): 03-02 You and your friend can celebrate together! Too bad! The party is on Wednesday, a school night. Please enter your birthday (MM-DD): 11-25 Please enter a friend's birthday (MM-DD): 12-01 Your birthday comes first! Great! The party is on Friday, a weekend night.
答案 0 :(得分:2)
checkNight(date)
。datetime.strptime
应该阅读datetime.datetime.strptime
。 '2011-'+date
)中日期的串联也可能导致错误。checkNight(date)
函数未返回任何内容也许这更接近你想要的东西:
import datetime
def get_date(prompt):
while True:
user_input = raw_input(prompt)
try:
user_date = datetime.datetime.strptime(user_input, "%m-%d")
user_date = user_date.replace(year=2011)
break
except Exception as e:
print "There was an error:", e
print "Please enter a date"
return user_date
def checkNight(date):
return date.strftime('%A')
birthday = get_date("Please enter your birthday (MM-DD): ")
another_date = get_date("Please enter another date (MM-DD): ")
if birthday > another_date:
print "Your friend's birthday comes first!"
print checkNight(another_date)
elif birthday < another_date:
print "Your birthday comes first!"
print checkNight(birthday)
else:
print "You and your friend can celebrate together."
请注意,由于我在用户输入后立即更改了2011年,我可以在checkNight()
更简单地提取星期几。