python - 有没有办法计算用户生日之前的月份?
问题描述
我用 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)
。这应该可以解决问题。
解决方案
您的操作不正确:
你应该做:
result = (int(BornIn) - CurrentMonth)%12
当您的生日在明年时,Modulo 会在这里管理案例。如果没有模数,您将得到负面结果(在这里您不会有任何问题,因为我们在 12 月,所以您的生日不能在第 13 个月)
推荐阅读
- csv - 添加 csv 的第一行作为节点类型的属性 - Neo4J
- sql - 时间戳 SQL 中具有特定小时和分钟的条件
- laravel - Laravel:BroadcastWhen 等价于事件
- facebook - 你能通过他们的 API 下载你的 Facebook 数据吗?
- javascript - Array.filter 也能够映射对象数组是否正常?
- c# - 将数据从 csv 文件写入并将其转换为数组以使用数据 c#
- webview2 - 尝试执行传入函数时,WebView2 HostObjectToScript 抛出运行时 System.NotImplementedException 异常
- python - 从pyserial继承时模拟
- r - 在 Shiny 中保存动态生成的图
- c# - 为什么我不能从 Main() 方法访问其他成员?