使用Python获取当前年份

2024-09-28 05:27:43 发布

您现在位置: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)

输出正确。

错误消息:

<ipython-input-1-0eeb398a7422> in <module>
      5     bYear = today.year - age
      6     print("Born in: " + bYear)
----> 7 bYear()

<ipython-input-1-0eeb398a7422> in bYear()
      3 def bYear():
      4     age = input("How old are you: ")
----> 5     bYear = today.year - age
      6     print("Born in: " + bYear)
      7 bYear()

TypeError: unsupported operand type(s) for -: 'int' and 'str'```

Im missing something here, any help?

Tags: inyouinputagetodaydatetimedefipython
3条回答

使用input时,它返回一个字符串(字母)。你需要的是一个整数。使用int()函数可以将字符串更改为整数,如下所示:

age = int(input("How old are you: "))

但是等等,还是有错误!问题是,您只能将+用于相同类型的对象。不能将字符串“添加”到整数中。要解决此问题,请使用str()函数:

print("Born in: "+str(bYear))

所以现在它运行得很好

不过,还有一件事可能会导致后续问题。变量today不是一个“全局”变量,因此如果在bYear函数中对其进行任何更改,它们将不会传递到主程序。要解决此问题,请将global today行放在bYear函数的开头

以下是完整的工作代码:

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()

您需要将年龄转换为int,因为python将输入转换为str,还需要将bYear更改为str,以便使用+打印它

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()

这可能是因为您没有将输入类型更改为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: " + str(bYear))
bYear()

相关问题 更多 >

    热门问题