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.

The if statement runs a block of code (the indented portion) if the corresponding condition is True.

x = 5
if x == 5:
    x += 3
print(x)
8

An if statement can have a corresponding else statement which runs if the condition in the if statement is False.

x = 5
if x < 5:
    x += 3
else:               # Optional else
    x *= 2
print(x)
10

Multiple if statements can be chained together with elif statement.

x = 5
if x > 5 and 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

Conditionals can take many forms.

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 preceded by an if or elif statement but can be left out if not needed. elif statements must always be preceded 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 has 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 the condition eventually evaluates to False or else you will get an infinite loop.

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, Ctrl-Alt-Delete, or force quit 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 sequence 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. my_list[3]) as you’ve seen previously. However, it is often useful to be able to iterate through all of the elements in a sequence.

some_items = ['truck', 'car', 'semi']
for x in some_items:
   print(x)
truck
car
semi

The range function generates a list of integers.

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

You can iterate through letters of a string.

for letter in 'sugar lumps':
   print(letter)
s
u
g
a
r
 
l
u
m
p
s

You can iterate through two lists of the same length with the zip function.

some_items = ['truck', 'car', 'semi']
some_colors = ['red', 'green', 'blue']
# The zip function pulls out pairs of items
for item, color in zip(some_items, some_colors):  
   print('The {0} is {1}'.format(item, color))
The truck is red
The car is green
The semi is blue

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

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

<code> For inline code.
[sourcecode] For multiline code.