首页 > 解决方案 > 有没有办法计算用户生日之前的月份?

问题描述

我用 Python 做了一个生日程序,程序询问用户他出生的月份,然后计算用户生日之前的月份。

例如,用户输入数字 5,当前月份为 2,程序输出“距离生日还有 3 个月!”。

在他正确的生日之前,我不知道如何计算月份。

例子:

from datetime import datetime

def Birthday():
    CurrentMonth = datetime.now().month
    BornIn = input("What month were you born in ? - ")

    result = int(BornIn) + CurrentMonth
    if int(BornIn) == CurrentMonth:
        print("You have already Birthday in this month!")
    elif int(BornIn) > 12:
        print("Invalid Input!")
    else:
        print("You have", result , "monthes until your Birthday!")



Birthday()

我需要做什么数学运算来计算距离他生日的月份?

看第 7 行,我用+来计算,但显然它不起作用。

编辑:

我需要做result = CurrentMonth - int(BornIn)。这应该可以解决问题。

标签: python

解决方案


您的操作不正确:

你应该做:

result = (int(BornIn) - CurrentMonth)%12

当您的生日在明年时,Modulo 会在这里管理案例。如果没有模数,您将得到负面结果(在这里您不会有任何问题,因为我们在 12 月,所以您的生日不能在第 13 个月)


推荐阅读