简单的Python——函数

How old will I be in 2099?

john'sjust turned four and he wants to know how old he will be in various years inthe future such as 2090 or 3044. His parents can't keep up calculating this sothey've begged you to help them out by writing a programme that can answerPhilip's endless questions.

Your task is towrite a function that takes two parameters: the year of birth and the year tocount years in relation to. As Philip is getting more courious every day he maysoon want to know how many years it was until he would be born, so yourfunction needs to work with both dates in the future and in the past.

Provide output inthis format: For dates in the future: "You are ... year(s) old." Fordates in the past: "You will be born in ... year(s)." If the year ofbirth equals the year requested return: "You were born this veryyear!"

"..." areto be replaced by the number, followed and proceeded by a single space. Mindthat you need to account for both "year" and "years",depending on the result.

code1

def calculate_age(year_of_birth,current_year):

    result1 = current_year - year_of_birth

    result2 = year_of_birth - current_year

    if result1 >1:

        return 'You are %d years old.' %result1

    elif result1 ==1:

        return 'You are 1 year old.'

    elif result1 ==0:

        return 'You were born this very year!'

    elif result2 == 1:

        return 'You will be born in 1 year.'

    elif result2 >1 :

        return'You will be born in %d years.' % result2

 

code2:

def calculate_age(year_of_birth, current_year):

diff =abs(current_year - year_of_birth)

plural ='' if diff == 1 else 's'

if year_of_birth < current_year:

return 'You are {} year{} old.'.format(diff, plural)

elif year_of_birth > current_year:

return 'You will be born in {} year{}.'.format(diff, plural)

return 'You were born this very year!’




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值