If语句执行Else,即使If看起来是真的?

2024-04-24 05:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在捕获代码时出错。不管函数的输入是什么,它总是执行第一个if语句的else块。为什么要这么做?你知道吗

这是错误捕获代码:

def rgbtohex(r=0, g=0, b=0):
    '''Converts RGB values to hecadeximal values. Supports 3 integers, one list, or one tuple.'''
    if type(r) == 'int' and type(g) == 'int' and type(b) == 'int':
        if r > 255 or g > 255 or b > 255:
            raise ValueError('one or more arguments are above 255.')
    elif type(r) == 'list' or type(r) == 'tuple':
        if r[0] > 255 or r[1] > 255 or r[2] > 255:
            raise ValueError('one or more index values are above 255.')
        if g == 0 and b == 0:
            r = r[0]
            g = r[1]
            b = r[2]
        else:
            raise TypeError('rgb values not integers, single list, or single tuple.')
        return
    else:
        raise TypeError('one or more arguments are not integers.')
    ...

Tags: orandintegers代码ifmoretypeone
3条回答

even though If is true?

永远不要假设这一点。密码没有说谎。你知道吗

type(r)实际上是一个int(没有引号)时,type(r) == 'int'永远不会为真

试试print(type(r) == 'int')


别把你的类型串起来。你知道吗

例如,isinstance(r, int)确实看起来更好

至于检查列表、集合、元组等

In Python, how do I determine if an object is iterable?

您可以使用isinstance()方法,因为比较intstr总是False

所以你可以改变你的状况

if type(r) == 'int' and type(g) == 'int' and type(b) == 'int':
    # process

收件人:

if isinstance(r, int) and isinstance(g, int) and isinstance(b, int):
    # process

其他条件也一样。你知道吗

在Python中,整数类型是int,而不是字符串"int"。你知道吗

删除引号。你知道吗

tuplelist也是如此。你知道吗

这是一个容易犯的错误,因为像JavaScript和Lua这样的其他语言使用字符串来表示类型。但是在Python中(就像在Ruby中一样),类型是实际的对象,由标识符引用。你知道吗

肥皂盒

需要考虑的是:我看到您正在尝试创建一个函数,用户可以传递三个整数、一个元组或一个列表。你试图给你的呼叫者一些灵活性,这是值得称赞的,但你最终得到的是

  1. 对参数进行类型检查,这不是超级Pythonic,并且
  2. 对列表或元组使用名为r的参数!你知道吗

第二部分意味着有人可以打电话

rgbtohex(r=[21128123])

这有点奇怪。你知道吗

我要做的是把你的职能定义为

def rgbtohex(r = 0, g = 0, b = 0):
    ...

如果您的用户有一个列表或元组,他们将知道如何解包并按以下方式调用:

my_color = [21,128,123]
rgbtohex(*myColor)

我是这样做的:

def rgbtohex(r=0, g=0, b=0):
    if not all(c in range(256) for c in (r, g, b)):
        raise ValueError('Components must be in range 0...255')
    return '#{:02x}{:02x}{:02x}'.format(r, g, b)

assert(rgbtohex() == '#000000')
assert(rgbtohex(9, 20, 255) == '#0914ff')
assert(rgbtohex(9, b=20, g=192) == '#09c014')
assert(rgbtohex(*[11, 0, 0]) == '#0b0000')
// Negative tests left as an exercise for the reader ;-)

相关问题 更多 >