cosmogonies.net Blog of cosmogonies.net

careers
5May/120

APyTA_09: Looping and forking, logic’s basics.

APyTA_09: Looping and forking, logic's basics.

Keywords are special statement and are strictly forbidden to overwrite (as a variable or function/method), and represent the Kernel of Python mechanics.
In the following APyTAs I will try to explain them all, regrouped by categories. Your can have dynamically the list like that:

import keyword
for currentKeyword in keyword.kwlist:
  print(currentKeyword)

First let's have a quick look at the boolean keyword operator:
and #  (False and True) ==False (and because the first term is False, and' will not eval the second term)
or # (True or False) ==True (same mechanics here, 'or' will ignore second term if the first term is True)
not #Boolean unary operator  not True  False
is #Identity comparison (== is the equality comparison)

The most common snippet I can give to you here is a validation test to a user selection:

import pymel.core.general
MySelection = pymel.core.general.ls(transforms=True)
if( len(MySelection) >0 and type(MySelection[0]) == pymel.core.nodetypes.Transform) :
  #Manage here your logic safely, do all operations available on a Transform object.
else:
  print("Please select a transform object")

Looping is the basics for the logic building in script, so let's enumerate all their keyword related:
if #Open a scope if the condition is True
else #Coupled with if, open a scope if the condition is False
elif #Syntaxic contraction of else if
for #Create an iterative loop
in #Create a temp variable (the current element) to loop into a list
while #Create a conditional loop
break #Exit the current scope
continue #Go to next scope (or iteration in loop)

import pymel.core
Mode = 1
MAX_NUMBER=25

if(Mode==0):
  for i in range(MAX_NUMBER):
    pymel.core.modeling.polyCube()
elif(Mode==1):
  while(len(pymel.core.general.ls(geometry=True))<=MAX_NUMBER):  #The loop will stop when your condition is True. So be REALLY SURE to reach it!
    obj = pymel.core.modeling.polyCube()
    if obj[0]._name =="pCube6":
      continue
    elif obj[0]._name =="pCube10": #When reaching this test, the while exit, and you have just 10 cube created.
      break
    print("Creating:"+obj[0]._name) #This sentence will not be printed for pCube6 due to the continue statement.
else:
  print("Unsupported mode")

My advice is to avoid the 'while' looping when it is possible.
In the most common cases, believe me, you can enumerate the range of your objects-to-evaluate (It is often your scene objects, or part of it, filtered on some criteria).
The danger of the 'while' looping is a misunderstanding of your object manipulation (or about Maya self-refresh computation), and not anticipate a context-change (like Maya auto-renaming to avoid names conflict).

mail
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.

jobs
e-mail
profile