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?
使用
input
时,它返回一个字符串(字母)。你需要的是一个整数。使用int()
函数可以将字符串更改为整数,如下所示:但是等等,还是有错误!问题是,您只能将+用于相同类型的对象。不能将字符串“添加”到整数中。要解决此问题,请使用
str()
函数:所以现在它运行得很好
不过,还有一件事可能会导致后续问题。变量
today
不是一个“全局”变量,因此如果在bYear
函数中对其进行任何更改,它们将不会传递到主程序。要解决此问题,请将global today
行放在bYear
函数的开头以下是完整的工作代码:
您需要将年龄转换为int,因为python将输入转换为str,还需要将bYear更改为str,以便使用
+
打印它这可能是因为您没有将输入类型更改为int,并将其保留为字符串,但我不确定。如果您提供完整的堆栈跟踪,那就太好了。试试这个:
如果您希望代码不会崩溃(如果有人输入的不是整数),请尝试以下操作:
相关问题 更多 >
编程相关推荐