繁体   English   中英

我如何使这段代码更紧凑? (Python)

[英]How do i make this code more compact? (python)

birth_year = int(input("What year were you born: "))
current_year = int(input("What year is it: "))
name = input("What is your name: ")
age = current_year-birth_year
print("Your name is", name , "and you are", age , "years old.")

#询问您的出生年份、当年和您的姓名,然后它会计算您的年龄并打印您的年龄和姓名

代码很好! 但是,如果您想改进它,我会推荐一件事-不要询问当前年份,因为可以使用datetime模块轻松获取

from datetime import date

current_year = date.today().year

尽管

print("Your name is", input("What is your name: "), "and you are", int(input("What year is it: ")) - int(input("What year were you born: ")), "years old.")

会更紧凑,它不再容易阅读。 最好让它保持现在的状态。

编辑:您不仅应该考虑计算年份,还应该考虑计算日期。 您可能想看看 python 日期时间模块。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM