You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据年龄与当前日期(2018年)计算出生年份?含Python代码疑问

如何根据年龄和当前日期(2018年)计算出生年份?

嘿,我看到你想要实现根据年龄和2018年计算出生年份的功能,目前的代码还没完成这个核心逻辑,让我帮你修正并解释一下~

先说说现有代码的问题:

  • 你调用了input("Type your age here:")但没有把输入的结果保存到变量里,这样后续根本没法用这个年龄值来计算
  • 完全缺少了「2018减去年龄得到出生年份」的计算步骤

修正后的完整代码:

# 获取用户基础信息
name = input("What is your name? ")
hobby = input("What is your hobby? ")
favorite_color = input("What is your favorite color? ")

# 输出收集到的用户信息
print(f"Ah, so your name is {name}, your hobby is {hobby}, and your favorite color is {favorite_color}.")

# 处理年龄输入与出生年份计算
print("How old are you?")
# 关键:将输入的字符串转换为整数,因为input默认返回字符串类型
age = int(input("Type your age here: "))
# 按照你的逻辑计算出生年份
birth_year = 2018 - age

# 输出最终结果
print(f"Your birth year is approximately {birth_year}!")

几个重要的细节说明:

  • 类型转换:input()函数返回的是字符串类型,直接用它和整数2018相减会报错,所以必须用int()把输入的年龄转换成整数类型
  • 变量保存:一定要把输入的年龄赋值给一个变量(比如这里的age),这样才能在计算时调用它
  • 输出优化:我用了Python3.6+支持的f-string来格式化输出,相比你原来用的%s写法,它更直观、可读性更强,当然如果你习惯原来的写法,也可以改成:
    print("Ah, so your Name is %s, your Hobby is %s, and your favorite Color is %s. " % (name, hobby, favorite_color))
    print("Your birth year is approximately %d!" % birth_year)
    

另外小提醒:如果用户在2018年还没过生日,实际出生年份可能是birth_year + 1,不过按照你给定的「2018减去年龄」的逻辑,上面的代码已经完全满足需求啦~

内容的提问来源于stack exchange,提问作者Constantin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:54:51