如何在Python中限制输入为0.5的倍数且处于0-10区间?
分数0.5倍数校验的实现方案
要判断输入值是否为0.5的倍数,核心逻辑是将输入值乘以2后验证是否为整数——因为所有0.5的倍数(比如0、0.5、1...10)乘以2都会得到整数。同时,建议用循环替代单次if判断,确保用户输入符合要求后才继续执行。
修复后的单分数校验代码
score1 = None while score1 is None: try: input_val = float(input("Please input the first score: ")) # 校验数值范围 if input_val < 0 or input_val > 10: print("Error! Scores can only be between 0 and 10.") continue # 校验0.5倍数:乘2后是否为整数 if round(input_val * 2) != input_val * 2: print("Error! Scores must be multiples of 0.5.") continue # 校验通过,赋值 score1 = input_val except ValueError: print("Error! Please enter a valid number.")
关键逻辑说明
- 循环校验:用
while循环反复提示输入,直到用户提供符合要求的值,避免单次校验后仍可能存在非法输入的问题。 - 浮点数精度处理:使用
round()函数处理浮点数精度误差(比如0.5在二进制中是精确的,但某些类似2.0000000001的近似值会被误判),确保判断准确。 - 非数字输入捕获:加入
try-except捕获用户输入非数字的情况,防止程序崩溃。
扩展到3个分数的总和计算
把校验逻辑封装成函数,避免重复代码,同时完成总和计算:
def get_valid_score(prompt): while True: try: input_val = float(input(prompt)) if not (0 <= input_val <= 10): print("Error! Scores can only be between 0 and 10.") continue if round(input_val * 2) != input_val * 2: print("Error! Scores must be multiples of 0.5.") continue return input_val except ValueError: print("Error! Please enter a valid number.") # 获取三个合法分数 score1 = get_valid_score("Please input the first score: ") score2 = get_valid_score("Please input the second score: ") score3 = get_valid_score("Please input the third score: ") # 计算并输出总和 total_score = score1 + score2 + score3 print(f"Total of the three scores: {total_score}")
内容的提问来源于stack exchange,提问作者TaxingClock
相关产品推荐
相关产品推荐

