我目前正在创建一个程序,它会要求用户输入年份,然后通过查看年份是否可以被 4 整除来说明它是否是闰年。它还有一个类型检查、存在检查和长度检查.我不断收到 AttributeError: 'int' object has no attribute 'isnumeric'
总而言之,该程序运行良好,如我所愿(下面的代码),但是当程序完成时,它会指出上述属性错误。为什么会显示该消息,我该如何解决?
代码:
print("Did you know that the last leap year was in 2020?")
print("To find out if a year is a leap year, use this program")
year = input("Please enter a year\n")
year = str(year)
valid = False
while valid == False:
if year == "":
print("Error. Please enter a year - it should be 4 digits long.")
year = input("Please enter a year\n")
year = year.decode(year)
valid == False
else:
if year.isnumeric() == False:
print("Error. Please enter a year - it should be 4 digits long.")
year = input("Please enter a year\n")
year = str(year)
valid == False
else:
if len(year) != 4:
print("Error. Please enter a year - it should be 4 digits long.")
year = input("Please enter a year\n")
year = str(year)
valid == False
else:
year = int(year)
rem = year%4
if rem == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year, unfortunately")
valid == True
您在此处将
year
设置为 int
:
else:
year = int(year)
然后
while
循环继续使用假设 year
仍然是 str
的代码,包括这一行:
else:
if year.isnumeric() == False:
注意
isnumeric
是 str
对象上的一个方法,告诉你它们是否可以转换为数字。 int
对象是数字所以他们没有这样的方法。
为了避免这个问题,我建议将获得有效
year
(作为int
)的代码部分与确定是否是闰年的代码部分分开:
print("Did you know that the last leap year was in 2020?")
print("To find out if a year is a leap year, use this program")
# First get the year.
while True:
try:
year = int(input("Please enter a year\n"))
if len(str(year)) != 4:
raise ValueError("wrong number of digits!")
break
except ValueError:
print("Error. Please enter a year - it should be 4 digits long.")
# year is now an int with 4 digits. Now figure out if it's leap.
if year % 4 == 0:
print(f"{year} is a leap year")
# Note: there is a bug here, leap year calculation
# is actually more complicated than this!
else:
print(f"{year} is not a leap year, unfortunately")
关于“获取有效 int”循环的一些一般说明,以及如何比您最初尝试的更简单地做这种事情:
input()
的结果转换为 str 或 decode
it。 input
只会返回一个 str
(在现代版本的 Python 中)。int
的所有原因并编写一堆 if
来防止它们,只需 try
转换并使用 except
来抓住失败时引发的ValueError
。这样一来,您只需编写一个错误检查,而无需在其他函数执行之前尝试对其进行逆向工程。try/except
,你可以在你的raise
的正文中使用一个try
自动跳转到相应的except
而不是必须写两次相同的错误处理代码。