鱼C论坛

 找回密码
 立即注册
查看: 945|回复: 4

[已解决]while语句不知道哪里错,帮帮小白

[复制链接]
发表于 2020-6-8 16:32:41 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
print('输入一个年份:',end=' ')
temp = input()
while not isinstance(temp,int):
    temp = input("抱歉,您的输入有误,请输入一个整数:")
year = int(temp)
if (year % 4 == 0) and (year % 100 != 0):
    print(temp + "这是闰年")
elif year % 400 == 0:
    print(temp + "这是闰年")
else:
    print("这不是闰年")


不管输入什么都是重复while循环语句
最佳答案
2020-6-8 16:34:23
本帖最后由 Twilight6 于 2020-6-8 16:35 编辑

因为 input 返回的是字符串类型 不能通过isinstance方法来判断是否是整型

用字符串方法 isdigit() 若字符串只包含数字 返回 True 否则 返回 False


  1. print('输入一个年份:',end=' ')
  2. temp = input()
  3. while not temp.isdigit():
  4.     temp = input("抱歉,您的输入有误,请输入一个整数:")
  5. year = int(temp)
  6. if (year % 4 == 0) and (year % 100 != 0):
  7.     print(temp + "这是闰年")
  8. elif year % 400 == 0:
  9.     print(temp + "这是闰年")
  10. else:
  11.     print("这不是闰年")
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-6-8 16:34:23 | 显示全部楼层    本楼为最佳答案   
本帖最后由 Twilight6 于 2020-6-8 16:35 编辑

因为 input 返回的是字符串类型 不能通过isinstance方法来判断是否是整型

用字符串方法 isdigit() 若字符串只包含数字 返回 True 否则 返回 False


  1. print('输入一个年份:',end=' ')
  2. temp = input()
  3. while not temp.isdigit():
  4.     temp = input("抱歉,您的输入有误,请输入一个整数:")
  5. year = int(temp)
  6. if (year % 4 == 0) and (year % 100 != 0):
  7.     print(temp + "这是闰年")
  8. elif year % 400 == 0:
  9.     print(temp + "这是闰年")
  10. else:
  11.     print("这不是闰年")
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-8 16:34:33 | 显示全部楼层
input接收的输入永远是字符串,你可以用isdigit
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-8 16:59:11 | 显示全部楼层
Twilight6 发表于 2020-6-8 16:34
因为 input 返回的是字符串类型 不能通过isinstance方法来判断是否是整型

用字符串方法 isdigit() 若字 ...

牛,最佳一天不到就上涨了好多
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-6-8 17:01:20 | 显示全部楼层
xiaosi4081 发表于 2020-6-8 16:59
牛,最佳一天不到就上涨了好多

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-21 14:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表