Chad Vernon
  • Home
  • Reel/Resume
  • Work
  • Resources
  • About
  • Contact
Home » Resources » Python Scripting for Maya Artists » Data Types and Variables
sideBar

Search

Categories

  • CG
  • cvxporter
  • Maya
    • API
    • Plug-ins
  • Personal

Archives

  • August 2010
  • 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

Data Types and Variables

Now that we know how to setup and run Python scripts, we can start learning how to write Python scripts.

Variables

The most common concept in almost all scripting and programming languages is the variable. A variable is a storage container for some type of data:

Figure 10 - Variables

Figure 10 - Variables

Variables allow us to store data in order to use it later. Variables, sometimes called identifiers, must start with a non-numeric character or underscore (_), may contain letters, numbers, underscores (_). Identifiers are case sensitive. It is always a good idea to name your variables with descriptive names so your code is easy to read.

Legal variable names

  • numberOfJoints
  • button1
  • teeth_geometry
  • _particleEffect

Illegal variable names

  • finger.nail
  • 4vertexEdgeId
  • cluster-handle

Python is a dynamically typed language. This means that a variable can hold one type of value for a while and then can hold another type later.

x = 5
x = 'Now x holds a string'

Not all languages allow you to do this. For example, in MEL, you have to declare a variable as an integer and then that variable can only hold an integer. This is what is known as a statically typed language.

Numbers and Math

There are 5 different types of number representions in Python: integers, long integers, floating-point, octal/hex, and complex numbers. The two representations that you will work with the most are integers and floating-point literals. Integers are numbers without a decimal point. Floating-point numbers are numeric values with a decimal point.

Integers

  • 43
  • -9234
  • 6

Floating-point

  • 1.324
  • -23.5325
  • 6.2

Python supports all the math operators that you would want to use on these numbers.

x = 4 + 5          # Addition
y = x – 8          # Subtraction
y = y * 2.2        # Multiplication
z = y / 1.2        # Division
z = z ** 4         # Power
z = -z             # Negation
a = 10 % 3         # Modulus (division remainder)
x += 2             # Addition and store the result back in x, same as x = x + 2
x -= 2             # Subtraction and store the result back in x
x *= 2             # Multiplication and store the result back in x
x /= 2             # Division and store the result back in x

Notice in some of these statements, I use the same variable on both the right and left side of the assignment operator (=). In most programming languages, the right side is evaluated first and then the result is stored in the variable on the left. So in the statement y = y * 2.2, the expression
y * 2.2 is evaluated using the current value of y, in this case 1, and then the result (1 * 2.2) = 2.2 is stored in the variable y.
Math operators have a precedence of operation. That is, some operators always execute before others even when in the same expression. For example the following two lines give different results:

print (5 + 3.2) * 2
16.4
print 6 + 3.2 * 2
12.4

Multiplication and division always get evaluated before addition and subtraction. However, you can control which expressions get evaluated first by using parentheses. Inner most parentheses always get evaluated first.

3 * (54 / ((2 + 7) * 3)) – 4
3 * (54 / (9 * 3)) – 4
3 * (54 / 27) – 4
3 * 2 – 4
6 – 4
2

When you mix integers and floating-point values, the result will always turn into a floating-point:

4 * 3.1
# Result: 12.4 #

However, you can explicitly turn an int to a float or a float to an int.

int(4 * 3.1)
# Result: 12 #
float(12)
# Result: 12.0 #

Strings

Strings are text values. You can specify strings in single, double or triple quotes.

'This is a string'                           # Single quotes
"This is also a string"                      # Double quotes
"""This string can span multiple lines"""    # Triple quotes

Single and double quoted strings are the same. The main thing to keep in mind when using strings are escape sequences. Escape sequences are characters with special meaning. To specify an escape code, you use the backslash character followed by a character code. For example a tab is specified as ‘\t’, a new line is specified as ‘\n’. You have to be mindful whenever escape sequences are involved because they can lead to a lot of errors and frustration. For example, in Windows, paths are written using the backslash: (e.x. C:\tools\new). If you save this path into a string, you get unexpected results:

print "C:\tools\new"
C:	ools
Ew

Python reads the backslashes as an escape sequence. It thinks the ‘\t’ is a tab and the ‘\n’ is a new line. To get the expected results, you either use escaped backslashes or a raw string:

>>> print "C:\\tools\\new"
C:\tools\new
>>> print r"C:\tools\new"
C:\tools\new

You can concatenate strings together with the + operator.

>>> x = 'I am '
>>> y = '25 years old.'
>>> print x + y
I am 25 years old.

However, you cannot add a string and a number.

>>> x = 'I am '
>>> y = 25
>>> print 'I am ' + y
# Error: cannot concatenate 'str' and 'int' objects
# Traceback (most recent call last):
#   File "", line 3, in
# TypeError: cannot concatenate 'str' and 'int' objects #

Python will throw an error saying you cannot concatenate a string and an integer. You can fix this in a couple different ways. The easiest is to convert the integer to a string.

>>> x = 'I am '
>>> y = 25
>>> print 'I am ' + str(y)
I am 25

A better way is to use string formatting. String formatting allows you to code multiple string substitutions in a compact way. You use string substitution with the % operator.

>>> x = 'I am '
>>> y = '25 years old.'
>>> print ‘%s%s’ % (x, y)
I am 25 years old.
>>> x = 'I am '
>>> y = 25
>>> print '%s%d’ % (x, y)
I am 25

To use string formatting, you provide a format string on the left of the % operator and the values you want to print on the right of the % operator. Different types of values have different format codes. Common codes include:

  • %s - string
  • %d, %i - integer
  • %f - floating-point

In the second example above, ‘%s%d’ % (x, y) contains two format codes, a string followed by an integer. On the right side of the % operator, we need to specify a value for each of the format codes in the order they appear in the format string. String formatting not only lets us code in a more compact way, it also lets us format values for output:

>>> print '%03d' % 5
005
>>> print '%+03d' % 6
+06
>>> print '%+03d' % -4
-04
>>> print '%.5f' % 4.4242353534
4.42424

With string formatting we can specify decimal precision, how many spaces a number should be printed with, whether to include the sign, etc. This is especially useful when printing out large tables of data.

String Methods

Methods are chunks of code that perform some type of operation. We will learn more about methods, also known as functions, in more detail later on, but now is a good time to introduce you to the syntax of calling a method. We call a method using the dot operator (.):
object.method()
An object is an instance of a particular type. For example, we could have a string object.

>>> x = 'This is a string.'    # x is a string object
>>> y = 'Another string.'      # y is another string object

When we read the code, someObject.someMethod(), we say we are calling the method named someMethod from the object called someObject. Most objects have many callable methods. Below are some of the methods found in string objects:

>>> x = 'This is my example string.'
>>> print x.lower()
this is my example string.
>>> print x.upper()
THIS IS MY EXAMPLE STRING.
>>> print x.replace('my', 'your')
This is your example string.
>>> print x.title()
This Is My Example String.
>>> print x.endswith('ng.')
True
>>> print x.endswith('exam')
False

Some of the methods have arguments in the parentheses. Many methods allow you to pass in values to perform operations based on the arguments. For example x.replace(‘my’, ‘your’) will return a copy of string x with all of the ‘my’ instances replaced with ‘your’. There are many methods available for many different types of objects and there is no need to memorize them. You will begin to memorize them after using them a lot. You can find help documentation for all objects with the help command.

help(str)

The help command will print out the documentation associated with an object, class, or function.

Lists

Lists are sequences or arrays of data. Lists allow us to use organized groups of data in our scripts.

>>> listOfLights = ['keyLight', 'rimLight', 'backLight', 'fillLight']
>>> print listOfLights[0]     # print the first element
keyLight
>>> print listOfLights[2]     # print the third element
backLight
>>> print listOfLights[3]     # print the fourth element
fillLight
>>> print listOfLights[-1]    # print the last element
fillLight
>>> print listOfLights[0:2]   # print the first through second elements
['keyLight', 'rimLight']
>>> print len(listOfLights)   # print the length of the list
4

We can access elements in a list with a numeric index. The indices start at index 0 and increment with each value in the list. We can also access subsets of lists with slicing

>>> print listOfLights[0:2], listOfLights[:3], listOfLights[:-1]
['keyLight', 'rimLight'] ['keyLight', 'rimLight', 'backLight'] ['keyLight', 'rimLight', 'backLight']
>>> listOfLights[0:2] = ['newLight', 'greenLight']
>>> print listOfLights
['newLight', 'greenLight', 'backLight', 'fillLight']

When an index is negative, it counts from the end of the list back. Lists can also contain mixed types of data including other lists.

>>> myList = [3, ‘food’, [‘anotherList’, 4 * 2, ‘dog’], 80.3]
>>> print myList[2][1]
8

When you try to access an element that does not exist, Python will throw an error.

>>> print myList[34]
# Error: list index out of range
# Traceback (most recent call last):
#   File "", line 1, in
# IndexError: list index out of range #

Lists, like strings, have their own set of methods available.

>>> listOfLights = ['keyLight', 'rimLight', 'backLight', 'fillLight']
>>> listOfLights.sort()
>>> print listOfLights
['backLight', 'fillLight', 'keyLight', 'rimLight']
>>> listOfLights.reverse()
>>> print listOfLights
['rimLight', 'keyLight', 'fillLight', 'backLight']
>>> listOfLights.append('newLight')
>>> print listOfLights
['rimLight', 'keyLight', 'fillLight', 'backLight', 'newLight']

This concept of indexing is not unique to lists. We can actually access strings the same way.

>>> x = 'Eat your vegetables'
>>> print x[0:6]
Eat yo
>>> print x[:-9]
Eat your v
>>> print x[5:]
our vegetables
>>> print x.find('veg')
9
>>> print x.split('e')
['Eat your v', 'g', 'tabl', 's']

You can think of strings as lists of characters. The main difference is strings cannot be edited in place with indices. For example, the following is illegal.

>>> x[4] = 't'
# Error: 'str' object does not support item assignment
# Traceback (most recent call last):
#   File "", line 1, in
# TypeError: 'str' object does not support item assignment #

Strings are what are known as immutable objects. Once they are created, they cannot be changed. Lists on the other hand are mutable objects, meaning they can change internally.

Tuples

Tuples are the same as lists except they are immutable. They cannot be changed once created.

>>> myTuple = (5, 4.2, 'cat')
>>> myTuple[1] = 3
# Error: 'tuple' object does not support item assignment
# Traceback (most recent call last):
#   File "", line 1, in
# TypeError: 'tuple' object does not support item assignment #

What is the purpose of tuples? There are aspects of Python that use or return tuples. I’d say 99.9% of the time, you’ll be using lists. Just be aware that you cannot change a tuple when one eventually pops up.

Dictionaries

Dictionaries are like lists except their elements do not have to be accessed with numeric indices. Dictionaries are a type of look-up table or hash map. They are useful in storing unordered types of data.

>>> characters = {'male' : ['Derrick', 'Chad', 'Ryan'], 'female' : ['Olivia', 'Sarah', 'Zoe']}
>>> print characters['male']
['Derrick', 'Chad', 'Ryan']
>>> print characters['female']
['Olivia', 'Sarah', 'Zoe']
>>> # Same functionality, different syntax:
>>> characters = dict(male=['Derrick', 'Chad', 'Ryan'], female=['Olivia', 'Sarah', 'Zoe'])
>>> print characters['male']
['Derrick', 'Chad', 'Ryan']
>>> print characters['female']
['Olivia', 'Sarah', 'Zoe']

# Some methods of dictionaries
>>> print characters.keys()
['male', 'female']
>>> print characters.values()
[['Derrick', 'Chad', 'Ryan'], ['Olivia', 'Sarah', 'Zoe']]
>>> print characters.has_key('male')
True
>>> print characters.has_key('shemale')
False
>>> print 'female' in characters
True
# Elements can be added on the fly
>>> characters['alien'] = ['ET', 'Alf']
>>> characters[6] = 4.5

Booleans and Comparing Values

In many of your programs, you’ll need to determine the relationship between variables such as if values are equal or if a value is greater than or less than another. These comparisons return a boolean value. A boolean value is simply True or False. You have already seen these values returned in a few of the previous examples.

>>> # x == y tests is x is equal to y
>>> # x != y tests if x does not equal y
>>> # x > y tests if x is greater than y
>>> # x < y tests if x is less than y
>>> # x >= y tests if x is greater than or equal to y
>>> # x <= y tests if x is less than or equal to y
>>> x = 4.3
>>> y = 2
>>> 5 == 5, 5 == 8, x == y, x == 4.3
(True, False, False, True)
>>> x <= y, x > y, x == y + 2.3, x >= 93
(False, True, True, False)
>>> a = 'alpha'
>>> b = 'beta'
>>> a > b, a == 'alpha', a < b
(False, True, True)

The following values are also considered False:

>>> ''           # Empty strings
>>> []           # Empty lists
>>> {}           # Empty dictionaries
>>> 0.0          # 0 valued numbers
>>> None         # An empty value

The following values are considered True:

>>> 'text'       # Strings with any characters
>>> [2, 3]       # Lists with elements
>>> {3 : 4.5}    # Dictionaries with elements
>>> 2.3          # Non-zero numbers
Home » Resources » Python Scripting for Maya Artists » Data Types and Variables

© 2010 Chad Vernon