简体   繁体   中英

The Foundry Nuke – Issues with `elif` and `else` statements

So to make it simple, I'm writing a script in NUKE which aligns the selected nodes in the node graph into one straight line in the Y-axis. I'm having issues where I'm writing the elif statement which is either not functioning as I want to or it is giving me a syntax error.

So the basis of the function is:

ELSE STATEMENT - when selected only one node - error message pops up saying user has to select more than one node

ELIF STATEMENT - when selected two or more nodes which are in the same Y-axis - message showing they are already aligned

IF STATEMENT - when selected two or more nodes in different Y-axis - it should properly align all the nodes in a straight line

# Getting selected nodes and making them into a list

selNodes = nuke.selectedNodes()
list = []

for node in selNodes:
            n = node['ypos'].value()
            list.append(n)

# Defining the actual function

def alignY():

    # Aligning the selected nodes using average position of every node. 
    # Must select more than one node in order to get an average.

    if len(selNodes) > 1:

        total = sum(list)
        average = total / len(selNodes)

        for node in selNodes:
            n = node['ypos'].setValue(average)

    # Getting the position of a single node from the list
    firstNodePostion = list[0]

    # Checking position of the single node is equivalent to the average 
    # To prevent nodes aligning again)  

    elif average == firstNodePostion:
        nuke.message("Nodes already Aligned")

    # When no nodes or only one node is selected this message pops up         
    else:
        nuke.message("Select Two or more Nodes")

alignY()

You have to indent the lines of you code according to Python rules.

So you need to use 4 spaces per indentation level – look at PEP 8 .

import nuke

selNodes = nuke.selectedNodes()
list = []

for node in selNodes:
    n = node['ypos'].value()
    list.append(n)

def alignY():

    if len(selNodes) > 1:
        total = sum(list)
        average = total / len(selNodes)

        for node in selNodes:
            n = node['ypos'].setValue(average)
            firstNodePostion = list[0]

    elif average == firstNodePostion:
        nuke.message("Nodes already Aligned")

    else:
        nuke.message("Select Two or more Nodes")

alignY()

在此处输入图片说明

Now alignY() method works as expected.

在此处输入图片说明

Your problem is that you have a statement that is sitting between the if and the elif, which can cause a syntax error.

It's hard to tell though, because you have not provided the exact error message, but from a syntactical point, there shouldn't be another statement separating the if and the elif.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM