【发布时间】:2018-05-27 18:20:13
【问题描述】:
我想使用 datetime 模块和用户输入来制作一个简单的年龄计算器。这是我的代码:
from datetime import datetime
now = datetime.now()
if day == now.day and month == now.month:
age = now.year - year
if day != now.day or month != now.month:
age = now.year - age - 1
if now.year - year == -1:
print("Be serious, please.")
if now.year - rok < -1:
print("Be serious,please.")
print(age)
它给了我以下错误:age = now.year - rok - 1 TypeError: 不支持的操作数类型 -: 'int' 和 'str' 当我用我分配给它们的变量替换 now.day 和 now.month 和 now.year 时,它也会给我这个错误,唯一的区别是,它显示 current_year 而不是 now.year。
from datetime import datetime
now = datetime.now()
today = now.day
current_month = now.month
current_year = now.year
if day == now.day and month == now.month:
age = current_year - year
if day != now.day or month != now.month:
age = current_year - age - 1
if current_year - year == -1:
print("Be serious, please.")
if now.year - rok < -1:
print("Be serious,please.")
print(age)
【问题讨论】:
-
您没有在提供的代码中定义
day,month,year或rok并且age定义不明确。确保这些项目 a) 正确定义和 b) 它们的类型为int -
您所需要的只是不要将数据类型混合在一起。不能比较,例如整数 5 和字符串“5”,因为它等于失败。
rok是什么类型的数据?这是整数类型吗?我无法在任何地方的代码中看到它的定义。 -
哦。 Rok 应该是年,这个错误发生在我将变量名称翻译成英文时。
标签: python python-3.x