You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python编写RGB校验代码时if判断失效,合法输入仍报错误是什么原因?

故障原因

input() 函数默认返回字符串类型,原代码没有将输入值转换为整数就直接和0、255做数值比较,判断条件逻辑完全异常,所以无论输入什么内容都会触发所有错误提示。

修复代码

基础修复版(仅修复数值比较逻辑,输入非数字会抛出异常):

# 将输入值转为整数类型
r = int(input("Enter the red: "))
g = int(input("Enter the green: "))
b = int(input("Enter the blue: "))

if r < 0 or r > 255:
    print("Red number is incorrect.")

if g < 0 or g > 255:
    print("Green number is incorrect.")

if b < 0 or b > 255:
    print("Blue number is incorrect.")

优化版(兼容非数字输入场景,不会直接崩溃):

def input_rgb(color: str) -> int:
    while True:
        raw = input(f"Enter the {color}: ")
        try:
            val = int(raw)
            if 0 <= val <= 255:
                return val
            print(f"{color.capitalize()} number is incorrect.")
        except ValueError:
            print(f"{color.capitalize()} number is incorrect, please enter an integer.")

r = input_rgb("red")
g = input_rgb("green")
b = input_rgb("blue")

内容的提问来源于stack exchange,提问作者Лев

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:24:04