零基础python第五讲动动手求闰年
我写的这个为什么输入非数字时不会弹出最后一句话呢帮忙康康错在哪了谢谢!
temp=input("请输入一个整数:")
while temp.isdigit():
a=int(temp)
if ((a%4 == 0)and(a%100 != 0))or(a%400 == 0):
print("这是闰年!")
else:
print("这不是闰年!")
temp=input("请输入一个整数:")
continue
temp=input("抱歉,你的输入有误,请重新输入:")
你在倒数第二行写了个continue,能打印才怪 continue会无视后面语句进入下一轮循环,然后判断非数字,退出循环,所以不会执行到打印错误那一行 本帖最后由 Malphitee 于 2020-4-16 17:11 编辑
不是continue的原因,缩进不对
python是一个注重格式的语言,改成这样就行了
https://i.loli.net/2020/04/16/DXSlq5BKyfFQmJu.png
当输入不是数字时,不进入while,进入while语句的下一条语句去执行
https://i.loli.net/2020/04/16/nhXfSADLKUsJ29E.png 1.如楼上所说,去掉最后一行的缩进,看上去可以运行了,问题是,你输入了之后呢?什么不做退出程序有用吗?
2.再说continue,循环最后一句写这continue没有任何作用!没有需要忽略的语句,有没有都是回到循环判断句。
3.你这样写退出循环的机制就是输入非数字,随便输入个非数字就退出程序,不是挺好的吗?
所以,去掉最后两行,你这个程序可以运行,而且还不错,如果想输入非数字不退出,必须另外加入一个退出的机制,参考下面代码:
while True:
temp=input("请输入一个整数:")
if temp.lower()=='q':
break
elif temp.isdigit():
a=int(temp)
if ((a%4 == 0)and(a%100 != 0))or(a%400 == 0):
print("这是闰年!")
else:
print("这不是闰年!")
else:
print('抱歉,你的输入有误,',end='') 你应该是想实现这样的功能:
temp = input("请输入一个整数:")
while True:
a = int(temp)
if ((a % 4 == 0) and (a % 100 != 0)) or (a % 400 == 0):
print("这是闰年!")
else:
print("这不是闰年!")
temp = input("请输入一个整数:")
while not temp.isdigit(): # 当用户输入的数不是数字时执行循环
temp = input("抱歉,你的输入有误,请重新输入:")
页:
[1]