而带有datetime函数的While循环将不起作用

2024-06-02 11:10:18 发布

您现在位置:Python中文网/ 问答频道 /正文

由于某些原因,这个while循环似乎不会执行。可能有人能帮我吗? 编辑:循环现在可以工作了,但现在循环中的更改只是返回一个无限重复的字符串,即0559年7月15日

就本计划而言,其目的是计算圣哈巴谷节日的某些日期,该节日以256天为间隔。它用于打印第0、10、20世纪第一个节日以及即将到来的节日及其序号值。 到目前为止,这是一个不完整的代码

from datetime import date, datetime, timedelta
origD = date(559, 7, 14)
print(f"0th Feast day: {origD.strftime('%B'), origD.strftime('%d'), origD.strftime('%Y')}")
day = int(origD.day)
month = int(origD.month)
year = int(origD.year)

dNow = date.today()
yearNow = int(dNow.year)
monthNow = int(dNow.month)
dayNow = int(dNow.day)

daysToFeast = int(0)
whichFeast = int(0)

while not (day == dayNow and month == monthNow and year == yearNow):
    nextDay = timedelta(1)
    newDate = origD + nextDay
    daysToFeast += 1  
    day = int(newDate.day)
    month = int(newDate.month)
    year = int(newDate.year)

    if daysToFeast == 256:
        whichFeast += 1
        daysToFeast = 0

    if whichFeast == 10:
        print(f"10th Feast day: {newDate.strftime('%B'), newDate.strftime('%d'), newDate.strftime('%Y')}")
    if year == 1900:
        print(f"First 20th Century Feast day: {newDate.strftime('%B'), newDate.strftime('%d'), newDate.strftime('%Y')}")

'''


Tags: dateifyearintprintdaywhilemonth
2条回答

忽略其余代码,循环不会启动,因为

while not day == dayNow and month == monthNow and year == yearNow:

(这与

while not (day == dayNow) and (month == monthNow) and (year == yearNow):

总是返回False)

试一试

while not (day == dayNow and month == monthNow and year == yearNow):

notandor这样的布尔运算具有precedence rules,它们控制表达式中的哪些操作首先应用于哪些参数

例如,notand具有更高的优先级(“绑定”更紧密)。所以上面的while条件实际上等于:

(not day == dayNow) and (month == monthNow) and (year == yearNow)

这将是False比你打算的要早

相反,您可以对表达式进行分组,以明确您的意图并覆盖优先规则,例如

not (day == dayNow and month == monthNow and year == yearNow)

这样做可以执行while循环体,但会暴露出一些其他问题。一旦你遇到这些问题,解决方案可能会变得显而易见。尽管如此,我还是要说,您的代码可以大大缩短和简化

例如,当datetime模块可以单步执行天(somedate += timedelta(days=1))并为您维护这些信息时,为什么还要为天、月、年等维护单独的变量呢?这肯定会使while条件更具可读性(not date1 == date2),并可能帮助您(和StackOverflow参与者)确定问题的来源。以下是我的尝试,使您的代码更加简洁,并打印第10个“节日日”:

from datetime import date, timedelta


then = date(559, 7, 14)
print(f"0th Feast day: {then.strftime('(%B, %d, %Y)')}")

now = date.today()
print(f"Today: {now.strftime('(%B, %d, %Y)')}")

whichFeast = 0

while then < now:
    then += timedelta(days=256)
    whichFeast += 1
    if whichFeast == 10:
        print(f"10th Feast day: {then.strftime('(%B, %d, %Y)')}")

相关问题 更多 >