用Python获取当前年份

import datetime
today = datetime.datetime.now()
def bYear():
    age = input("How old are you: ")
    bYear = today.year - age
    print("Born in: " + bYear)
bYear()

我几天前开始学习python。尝试一些“愚蠢”的东西,但我无法使此代码正常工作。 如果我尝试用以下方式打印年份:

print(today.year)

输出正确。 我在这里想念什么,有什么帮助吗?

评论
禁锢的誓言
禁锢的誓言

You need to convert your age as int as python takes input as str. And also change the bYear to str to print it using +.

import datetime
today = datetime.datetime.now()
def bYear():
    age = int(input("How old are you: "))
    bYear = today.year - age
    print("Born in: " + str(bYear))
bYear()
点赞
评论
wnihil
wnihil

尝试这个:

from datetime import datetime
year = datetime.now().year
print(year)
点赞
评论
Buck
Buck

The only real problem in your code is that you're not converting the input (which is a string) to integer to do the operation you want afterwards. You must be getting a TypeError, right?

Just change this: age = input("How old are you: "), with this:

age = int(input("How old are you: "))
点赞
评论
aut_id
aut_id

这可能是因为您没有将输入类型更改为int,而是将其保留为字符串,但是,我不确定。如果您提供了完整的堆栈跟踪信息,那就太好了。尝试这个:

import datetime
today = datetime.datetime.now()
def bYear():
    age = int(input("How old are you: "))
    bYear = today.year - age
    print("Born in: " + bYear)
bYear()

如果您希望代码不崩溃(如果有人输入的不是整数),请尝试以下操作:

import datetime
today = datetime.datetime.now()
def bYear():
    age = input("How old are you: ")
    if not age.isdigit():
        print("Invalid input!")
    else:
        age = int(age)
    bYear = today.year - age
    print("Born in: " + bYear)
bYear()
点赞
评论