用python计算退休时间怎么搞呀

img


如图如图,还有个挑战题,处理程序返回负数的情况,提示用户已经可以退休了

我的思路如下:

1、用两个input来获取年龄和退休年龄;

2、用退休年龄减去年龄计算得出要工作的年数;

3、判断要工作的年数是否大于0,大于0则打印工作年数,然后计算到哪一年退休;如果要工作的年数小于等于0,则提示可以退休了。

代码如下:

参考链接:
https://jingyan.baidu.com/article/0964eca21fd2a3c384f53612.html
Python time.localtime()用法及代码示例 - 纯净天空

import time

age = int(input("What is your current age? ")) #获取年龄
retireAge = int(input("At what age would you like to retire? ")) #获取退休年龄
workTime = retireAge-age  #退休年龄减去年龄即还需要工作的年数


if workTime>0:  #如果工作的年数大于0,则打印还要工作多少年,到哪一年退休
    print("You have "+str(workTime)+" years left until you can retire.") #打印还要工作多少年
    #https://jingyan.baidu.com/article/0964eca21fd2a3c384f53612.html
    #https://vimsky.com/examples/usage/python-time-localtime-method.html
    localtime = time.localtime(time.time())  #获取系统时间对象
    thisYear = localtime[0]  #从系统时间对象中的年份
    retireYear = thisYear + workTime #退休年份即今年加上工作的年数
    print("It's "+str(thisYear)+", so your can retire in "+str(retireYear)+".") #打印退休年龄
else : #如果工作年数小于等于0,则提示可以退休了
    print("You can retire now.")
    




img

from datetime import datetime

currentAge = int(input("What is your current age? "))
retireAge = int(input("At what age would you like to retire? "))
thisYear = datetime.today().year
d = retireAge-currentAge
if d<0:
    print("You should have retired now.")
else:
    print(f"You have {d} years left until you can retire.")
    print(f"It's {thisYear}, so you can retire in {thisYear+d}")