Chad Vernon
  • Home
  • Reel/Resume
  • Work
  • Resources
  • About
  • Contact
Home » Resources » Python Scripting for Maya Artists » Controlling the Flow of Execution
sideBar

Search

Categories

  • CG
  • cvxporter
  • Maya
  • Personal

Archives

  • July 2010
  • May 2010
  • April 2010
  • March 2010
  • December 2009
  • October 2009
  • September 2009
  • August 2009
  • July 2009
  • June 2009
  • May 2009
  • April 2009
  • March 2009
  • February 2009
  • January 2009
  • December 2008
  • November 2008
  • October 2008
  • September 2008
  • August 2008
  • July 2008
  • June 2008
  • May 2008
  • April 2008
  • March 2008
  • February 2008
  • January 2008
  • December 2007
  • November 2007
  • October 2007
  • September 2007
  • August 2007

Rss

  • Main Entries RSS
  • Comments RSS

Controlling the Flow of Execution

All the scripts so far have been executed line by line. In most of your scripts, you will need to be able to control the flow of execution. You will need to execute code only if certain conditions are met and you will need to execute code multiple times. This is called the logic of the script. Python, like most other languages, supports the basic constructs to accomplish this.

Conditionals

To execute code only if a condition is True or False, you use the if, elif, and else statements.

>>> x = 5
>>> if x == 5:
>>>     x += 3
>>> print x
8
>>> x = 5
>>> if x < 5:
>>>     x += 3
>>> else:               # Optional else
>>>     x *= 2
>>> print x
10
>>> x = 5
>>> if x > 5 and not x == 2:
>>>     x += 2
>>> elif x == 5:        # Optional elif
>>>     x += 4
>>> elif x == 9:        # Optional elif
>>>     x -= 3
>>> else:               # Optional else
>>>     x *= 2
>>> print x
9
>>> x = 5
>>> if x == 5:
>>>     x += 3
>>> if x == 8:
>>>     x *= 2
>>>     if x == 16
>>>         x -= 10
>>> print x
6
>>> x = ['red', 'green', 'blue']
>>> if 'red' in x:
>>>     print 'Red hot!'
Red hot!

if statements let you select chunks of code to execute based on boolean values. In a sequence of if/elif/else statements, the first if statement is evaluated as True or False. If the condition is True, the code in its corresponding code block is executed. If the condition is False, the code block is skipped and execution continues to the next else or elif (else if) statement if one exists. else statements must always be preceeded by an if or elif statement but can be left out if not needed. elif statements must always be preceeded by and if statement but can left out if not needed.

Code Blocks

Code blocks are chunks of code associated with another statement of code. Take the following code for example.

>>> x = 'big boy'
>>> y = 7
>>> if x == 'big boy' and y < 8:
>>>     print 'Big Boy!'
>>>     y += 3

The last two lines are in the code block associated with the if statement. When the condition of the if statement is evaluated as True, execution enters the indented portion of the script. Code blocks in Python are specified by the use of whitespace and indentation. You can use any number of spaces or even tabs, you just have to be consistent throughout your whole script. However, even though you can use any amount of whitespace, the Python standard is 4 spaces. Code blocks can be nested in other code blocks, you just need to make sure your indentation is correct.

>>> x = 5
>>> y = 9
>>> if x == 5 or y > 3:
>>>     x += 3
>>>     if x == 8:
>>>         x *= 2
>>>     elif y == 7:
>>>         y -= 3
>>>         if x == 16 or y < 21:
>>>             x -= 10
>>>     else:
>>>         y *= 3
>>> else:
>>>     x += 2
>>> print x
16
>>> print y
9

if/elif/else statements that are chained together need to be on the same indentation level. Read though the previous example and work out the flow of execution in your head or on paper.

While Loops

While loops allow you to run code while a condition is True.

>>> x = 5
>>> while x > 1:
>>>     x -= 1
>>>     print x
4
3
2
1

In the above example, the condition is tested as True, so execution enters the code block of the while loop. When execution reaches the print statement, the value of x as been decremented and execution returns to the while statement where the condition is tested again. This loop continues until the condition is False. You have to take care that this condition is eventually gets a False value.

>>> x = 5
>>> while x > 1:
>>>     x += 1

In the above example, x will continue to increment and the condition will always be True. This is called an infinite loop. If you create one of these, you’ll have to shut down your program or Ctrl-Alt-Delete out of Maya.
Sometimes you will want to exit out of a loop early or skip certain iterations in a loop. These can be done with the break and continue commands.

>>> x = 0
>>> while x < 10:
>>>     x += 1
>>>     if x % 2:
>>>         continue    # When x is an odd number, skip this loop iteration
>>>     if x == 8:
>>>         break       # When x == 8, break out of the loop
>>>     print x
>>> else:               # This optional else statement is run if the loop finished
>>>     x = 2           # without hitting a break
2
4
6
>>> # This code causes an infinite loop, try to find out why.
>>> x = 0
>>> while x < 10:
>>>     if x % 2:
>>>         continue
>>>     if x == 8:
>>>         break
>>>     print x
>>>     x += 1

For Loops

For loops iterate over sequences objects such as lists, tuples, and strings. Sequence objects are data types comprised of multiple elements. The elements are usually accessed by square brackets (e.g. myList[3]) as you’ve seen previously. However, it is often useful to be able to iterate through all of the elements in a sequence.

>>> someItems = ['truck', 'car', 'semi']
>>> for x in someItems:
>>>    print x
truck
car
semi

>>> print range(5)        # Built-in function range creates a list of integers
[0, 1, 2, 3, 4]

>>> for x in range(5):
>>>     # Create a spine joint in Maya
>>>     pass              # pass is used when you have no code to write
>>> for letter in 'sugar lumps':
>>>    print letter,
s u g a r   l u m p s

>>> someItems = ['truck', 'car', 'semi']
>>> someColors = ['red', 'green', 'blue']
>>> # the zip function pulls out pairs of items
>>> for x, y in zip(someItems, someColors):
>>>    print 'The %s is %s' % (x, y)
The truck is red
The car is green
The semi is blue

>>> for i in range(0, 10, 2):      # range(start, stop, step)
>>>     if i % 2 == 1:
>>>         continue
>>>     if i > 7:
>>>         break
>>>     print i,
>>> else:                          # Optional else
>>>     print 'Exited loop without break'
0 2 4 6

Like the while loop, for loops support the continue, break, and else statements.

Home » Resources » Python Scripting for Maya Artists » Controlling the Flow of Execution

© 2010 Chad Vernon