【问题标题】:How do I get both functions to work at once in Python?如何让这两个函数在 Python 中同时工作?
【发布时间】:2011-03-15 17:52:46
【问题描述】:

我对这一切真的很陌生,现在我正在尝试获得两个功能来执行和打印,但我似乎无法掌握它:

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 需要能够检查较早的生日是哪一天晚上。

这里有一些例子:

请输入您的生日(MM-DD):11-25 请输入朋友的生日(MM-DD):03-05 你朋友的生日是第一位的! 伟大的!聚会是在星期六,一个周末的晚上。 请输入您的生日(MM-DD):03-02 请输入朋友的生日(MM-DD):03-02 你和你的朋友可以一起庆祝! 太糟糕了!聚会是在星期三,一个学校之夜。 请输入您的生日(MM-DD):11-25 请输入朋友的生日(MM-DD):12-01 你的生日是第一位的! 伟大的!聚会是在星期五,一个周末的晚上。

【问题讨论】:

标签: python datetime weekday


【解决方案1】:
  • 一个错误是由于调用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() 中更简单地提取星期几。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2013-05-28
    • 2020-08-04
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多