如何解决Python中while语句判断字符串输入出错的问题
Python字符串输入校验问题解答
核心问题说明
- 第一个误区:Python 3中
input()函数的返回值永远是字符串类型,不存在返回int/float的情况。你之前做int输入校验的逻辑是判断输入内容能不能转成int,而不是判断输入本身的类型是不是int,你现在的需求逻辑搞反了——如果你想校验的是「输入不能是纯数字内容」,而不是「输入类型不是字符串」,那你最初的需求理解就有偏差。 - 第二个语法错误:你写的
while response == int or float逻辑完全错误,or两边是独立判断条件,这段代码等效于while (response == int) or (bool(float) is True),而float作为内置类型本身布尔值永远为真,所以这个循环条件永远成立,会进入无限循环。你尝试的其他写法也存在类似逻辑问题:比如response == str是把变量值和类型对象直接比较,永远不会成立,自然不会触发循环。
正确实现方案
情况1:确实要校验输入类型为字符串(该场景下几乎不需要额外判断,因为input返回值必然是字符串)
response = input("please enter the value : ") # 该判断永远为假,不会进入循环 while not isinstance(response, str): print("Enter the value ") response = input("please enter the value : ")
情况2:真实需求为「输入不能是纯数字内容(无法转成int或float)」,这也是绝大多数同类需求的实际场景
while True: response = input("please enter the value : ") # 校验是否可转为int try: int(response) print("Enter the value ") continue except ValueError: pass # 校验是否可转为float try: float(response) print("Enter the value ") continue except ValueError: # 既不能转int也不能转float,为合法非数字字符串,退出循环 break
内容的提问来源于stack exchange,提问作者Bella Lee
相关产品推荐
相关产品推荐

