|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
# not操作符的作用是将布尔类型的结果翻转:即取反的意思,not True == Flase
while not isinstance(temp, int):
print("抱歉,输入不合法,", end='')
temp = input("请输入一个整数:")
while在这个语句中是什么意思啊
这里代码的理想作用是判断 temp 输入是否合法,但是这段代码是错误的
因为 input 函数返回的永远是字符串,而 isinstance 函数判断 temp 是否为 int 整型 就永不成立
即一定返回 False ,但是因为前面进行了 not 取反,那么就会导致 while 循环条件必成立,导致死循环
所以不能使用 isinstance 函数,你可以使用字符串方法 indigit() 函数来判断字符串是否是纯数字字符串
参考代码:
- temp = input("不妨猜一下小甲鱼现在心里想的是哪个数字:")
- while not temp.isdigit():
- print("抱歉,输入不合法,", end='')
- temp = input("请输入一个整数:")
- temp = int(temp)
- print("你输入的整数为:", temp)
复制代码
|
|