大约在第7行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了大约在第7行相关的知识,希望对你有一定的参考价值。

from datetime import date
name = input("what's your name?")
surname = input("what's your surname?")
birth_year = input("what's your birth year?")
initials = name[0] + surname[0]
current = date.today()
age = current.year - birth_year
print('your initials are ' + initials.upper() + ' and you are ' + str(age) + ' years old')
答案

您正在将int减去一个字符串。

python中的输入始终是字符串。因此,当您询问用户birth_year时,用户键入的数字将作为字符串进行评估。

因此age = current.year - birth_year实际上是:int - string

为避免这样做:

age = current.year - int(birth_year)
另一答案

请执行以下提到的更改,代码将正常工作。行号4已更改为接受int格式而不是字符串格式(这是输入的默认格式)的输入年份]

`from datetime import date
name = input("what's your name?")
surname = input("what's your surname?")
birth_year = int(input("what's your birth year?"))
initials = name[0] + surname[0]
current = date.today()
age = current.year - int(birth_year)
print('your initials are ' + initials.upper() + ' and you are ' + str(age) + ' years 
old')`

以上是关于大约在第7行的主要内容,如果未能解决你的问题,请参考以下文章