【问题标题】:Why is an integer variable used in an if statement?为什么在 if 语句中使用整数变量?
【发布时间】:2020-07-23 14:06:30
【问题描述】:

在下面的代码中,sn-p next_dot 用在 if 语句中,为什么?

def on_mouse_down(pos): 
    if dots[next_dot].collidepoint(pos): 
        if next_dot: 
            lines.append((dots[next_dot - 1].pos, dots[next_dot].pos))

        next_dot = next_dot + 1

    else:
        lines = []
        next_dot = 0

我不明白“if next_dot:”的作用以及它对这段代码有何贡献。

【问题讨论】:

    标签: python pgzero


    【解决方案1】:

    在 python 中,变量是“假”或“真”,这意味着当“if”语句将变量作为表达式求值时,它会给出假或真。假变量是例如空字符串、空列表、零和无,而真变量是具有值的变量,例如 [1,2,3] 或 'foo'。

    if 0:
        # this code will never run
    
    if []:
        # this code will never run
    
    if 1:
        # this code will always run
    

    如果 next_dot 为 0,您不想运行该函数,因为那样您会得到一个负索引,所以他放了一个 if 语句。

    【讨论】:

      【解决方案2】:

      欢迎来到堆栈溢出!对于数字,0 将始终评估为 False。其他一切都将评估为真。此外,因为它是一个数字,所以它可以递增,并且 if 块中的代码可以执行精确的次数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-10
        • 2013-09-17
        • 2022-12-09
        • 2017-03-02
        • 1970-01-01
        • 1970-01-01
        • 2017-10-13
        • 1970-01-01
        相关资源
        最近更新 更多