Python校验输入为指定范围整数/浮点数及循环校验问题求解
问题产生原因
- Python 3中
input()函数的返回值永远为字符串类型,你没有做类型转换直接调用isinstance(Monday,(int,float))做类型判断,结果永远为False,这是if分支始终不触发的核心原因。 - 你后续尝试的
if Monday != type(int)写法逻辑错误:type(int)的返回值是元类型type,和输入得到的字符串变量没有可比性,判断逻辑永远成立,因此仍然会进入else分支。
修复方案
正确的实现逻辑为:先尝试将输入的字符串转换为数值类型,通过捕获ValueError异常判断输入是否为合法数字,再校验数值是否在1-10的范围内。
修复后的代码如下:
def FeelingCalc(): # 直接使用死循环,符合条件时跳出即可,无需额外控制变量 while True: monday_input = input("On a scale of 1 to 10, how did you feel on Monday? ") try: # 转换为浮点数兼容整数、小数输入,若仅需整数可替换为int() monday_score = float(monday_input) except ValueError: # 转换失败代表输入不是合法数值 print("Please type a whole number between 1 and 10.") continue # 校验数值范围 if 0 < monday_score < 11: print("Alright. Let's move on.") break print("Please type a whole number between 1 and 10.")
内容的提问来源于stack exchange,提问作者Digitalvolt
相关产品推荐
相关产品推荐

