作业求助
005讲 1问中year = input("请输入年份:")
while not year.isdigit():
year = input("类型错误,请重新输入年份:")
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("此年是闰年")
else: print("此年非闰年")
提示
TypeError: not all arguments converted during string formatting
我仔细思考了很久也没想明白错在了哪里(真0基础萌新真心求助)
谢谢各位大佬 本帖最后由 jackz007 于 2019-10-6 00:43 编辑
year = input("请输入年份:") # input() 返回的是字符串类型,就是说,year 是字符串
. . . . . .
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):# 这里却把 year 直接当成整型数使用,所以出错。
这么改:
prompt = "请输入年份:"
while True:
year = input(prompt)
if year . isdigit():
break
prompt = "类型错误,请重新输入年份:"
year = int(year)
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("此年是闰年")
else:
print("此年非闰年")
要把年份转化成整形才可以进行计算:
year = input("请输入年份:")
while not year.isdigit():
year = input("类型错误,请重新输入年份:")
year = int(year)
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("此年是闰年")
else: print("此年非闰年") temp = input("请输入年份:")
year = int(temp)
while not year.isdigit():
temp = input("类型错误,请重新输入年份:")
year = int(temp)
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("此年是闰年")
else:
print("此年非闰年")
#input()返回的是字符串,可以用int()转化为整型, 错误提示告诉你:
类型错误:不是所有的数值在字符串格式化时转化成功。
从你的代码中可以看出来,你的year输出内容只是字符串,不是数值。
因此下面拿字符串和数字的比较无法进行。
页:
[1]